JavaScript 等待承诺

JavaScript wait for promise

我需要 fetchAndInstantiate 在定义 someVariable 之前等待(由外部进程)。函数 getResult 检测所述变量何时被定义。

我有这两个功能:

async function getResult(){
    if(typeof someVariable !== 'undefined'){
        console.log('yup');
        Promise.resolved(someVariable);
    }else{
        console.log('nop');
        setTimeout(getResult, 250);
    }
}

fetchAndInstantiate = async function(a, b, c){
    delete someVariable;
    console.log('called fetchAndInstantiate');
    document.dispatchEvent(new CustomEvent('wasmcall', {detail: { wasm_mod: a, function: b, args: c}}));
    await getResult().then(function(result){return result;});
}

function fetchAndInstantiate 调用 function getResult 我希望它等到 promise 解决。但是 getResult 在调用 setTimeout 时返回未定义的承诺。

如何让 getResult 仅在定义了 someVariable 时解析?

您可以创建异步延迟:

const delay = milliseconds => new Promise(resolve, setTimeout(resolve, milliseconds));

并在你的异步函数中使用它:

async function getResultAsync() {
    while (true) {
        if (typeof someVariable !== 'undefined') {
            return someVariable;
        }
        await delay(250);
    }
}

这将继续等待,直到 someVariable 被定义,每次检查之间有 250 毫秒的延迟,不会阻塞。

请注意,您必须 return 在异步函数中添加一些内容;这解决了 Promise 即 returned.

然后在你的fetchAndInstantiate函数中消费:

fetchAndInstantiate = async function(a, b, c) {
    delete someVariable;
    console.log('called fetchAndInstantiate');
    document.dispatchEvent(new CustomEvent('wasmcall', {detail: { wasm_mod: a, function: b, args: c}}));
    await getResultAsync();
}

您不需要将 awaitthen() 混用; await 为您取消 Promise 分辨率。

您必须确保 getResult returns 如您所愿。

此外,使用 setInterval 将完成您想要的,而无需那些混乱的代码。

async function getResult(){
    var result = await new Promise(function(resolve) {
    const interval = setInterval(function(){
      if(typeof someVariable !== 'undefined'){
        clearInterval(interval);
        resolve(someVariable);
      }
    }, 250);
  });
  return result;
}

fetchAndInstantiate = async function(a, b, c){
    delete someVariable;
    console.log('called fetchAndInstantiate');
    document.dispatchEvent(new CustomEvent('wasmcall', {detail: { wasm_mod: a, function: b, args: c}}));
    var result = await getResult();
    return result;
}