[英]Convert async await in while loop to promises
I can't figure out how to convert async await functionality in a while loop to a promise based implementation. 我无法弄清楚如何将while循环中的异步等待功能转换为基于Promise的实现。
repl showing the async await version 显示异步等待版本的repl
https://repl.it/repls/IdealisticPepperyCoding https://repl.it/repls/IdealisticPepperyCoding
var dependency = false; function checkDependency() { return new Promise(resolve => { setTimeout(() => { dependency = true; return resolve(); }, 1000) }); } async function isReady() { while(!dependency) { console.log('not loaded'); await checkDependency(); } console.log('loaded') } isReady();
If I'm understanding you correctly, you're wanting to use Promises without async functions instead of Promises with async functions, and the sample checkDependency
may actually not set dependency = true
in all cases, so you want to "loop." 如果我正确理解你,你想不使用异步函数,而不是与异步功能的承诺的承诺,和样品checkDependency
实际上可能没有设置dependency = true
在所有的情况下,所以要“循环”。
Equivalent functionality could look something like this, where you "recursively" call the check function. 等效功能可能看起来像这样,您可以“递归”调用检查功能。 It won't actually be recursive and lead to a stack overflow, though, since the call is done in an async callback: 由于调用是在异步回调中完成的,因此它实际上不会递归并导致堆栈溢出:
var dependency = false;
function checkDependency() {
return new Promise(resolve => {
setTimeout(() => {
dependency = true;
return resolve();
}, 1000)
});
}
function isReady() {
if (!dependency) {
return checkDependency().then(isReady);
}
return Promise.resolve(true);
}
isReady().then(() => {
console.log('loaded')
});
您不需要while循环。
checkDependency().then(() => { console.log('loaded');});
recolve()
just call it. 您无需返回recolve()
即可调用它。 then
within the function isReady
then
在函数isReady
调用该函数 function checkDependency() { return new Promise(resolve => { setTimeout(resolve, 1000); }); } function isReady() { console.log('not loaded'); checkDependency().then(() => { console.log('loaded') }); } isReady();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.