简单,在js中非常简单的等待

问题描述 投票:-1回答:2

我是新来的(但我知道“ 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

javascript wait synchronous
2个回答
0
投票

取决于完成后要执行的操作,您最好只调用一个函数,而不是将finish设置为true。

否则,您将不得不使用promise


0
投票

您可以使用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; }
© www.soinside.com 2019 - 2024. All rights reserved.