Your loop should be within an async function, and await the result of the call to getRandomWord
(您的循环应在异步函数内,并等待对getRandomWord
的调用结果)
async function doWork()
{
for (i=1; i<=10; i++) {
if (i%3 === 0) {
console.log(i + ": " + "divided" );
}
else {
var result = await getRandomWord()
console.log(i + ": " + result);
}
}
}
Live example below.(下面的直播示例。)
function getRandomWord() { return new Promise((resolve) => { setTimeout( () => resolve("Hello, World") ); }); } async function doWork() { for (i=1; i<=10; i++) { if (i%3 === 0) { console.log(i + ": " + "divided" ); } else { var result = await getRandomWord() console.log(i + ": " + result); } } } doWork()
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…