我是新来的(但我知道“ copy-paster” ^^)。我最近开始创建一种BASIC类型的编程语言,我用JS(很多JS ^^)进行解释。我设法创建了对象系统,变量等,尤其是用js创建的库,但是问题出在库“控制台”的“输入”功能中,为此我在“ pre”中添加了输入文本,我用作控制台,但是当输入为空时,代码将继续执行。我想要的很简单,这是一个愚蠢的“等待条件”:
var finish = false;
document.querySelector("#input").addEventListener(function(e) {
if(e.keyCode == 13) {
var inputText = document.querySelector("#input").value;
finish = true;
}
}
wait if(!finish))
//continue
或更简单:
//code
wait if(condition)
//continue after wait
Cordily,Manolo
取决于完成后要执行的操作,您最好只调用一个函数,而不是将finish
设置为true。
否则,您将不得不使用promise
您可以使用async functions and await
异步功能是允许使用await
关键字的功能。 await
关键字等待Promise
解析,因此您可以使函数返回一个Promise,并在准备继续时解析一些值。该值将返回到await
关键字。
async function main() {
log('enter your name:');
const name = await getInput();
log('Hello', name);
log('How old are you?');
const ageString = await getInput();
const age = parseFloat(ageString);
if (age > 55) {
log('Hello Boomer!');
} else if (age > 40) {
log('Hello Gen-Xer!');
} else if (age > 25) {
log('Hello Millenial!');
} else {
log('Hello Zoomer!');
}
}
main();
function getInput() {
return new Promise(resolve => {
const elem = document.createElement('input');
elem.type = 'text';
document.body.appendChild(elem);
elem.focus();
function handleInput() {
elem.removeEventListener('change', handleInput);
elem.disabled = true;
resolve(elem.value);
}
elem.addEventListener('change', handleInput);
});
}
function log(...args) {
const elem = document.createElement('pre');
elem.textContent = args.join(' ');
document.body.appendChild(elem);
}
input { display: block; }