【发布时间】:2020-10-31 08:49:49
【问题描述】:
我需要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;});
}
函数fetchAndInstantiate 调用函数getResult,我希望它等到承诺解决。但是当setTimeout 被调用时,getResult 正在返回一个未定义的承诺。
如何让getResult 仅在定义了 someVariable 时才解析?
【问题讨论】:
-
“当
setTimeout被调用时,BUTgetResult正在返回一个未定义的承诺” - 它总是会“返回”undefined,因为你没有返回任何东西(有用) 在getResult -
@Andreas 关于如何在不返回未定义的
getResult的情况下调用setTimeout的任何想法?
标签: javascript asynchronous async-await resolve