我有一个名为 promiseLoop
的函数,它返回一个代价高昂的操作(假设它是一个大循环)。现在,当我运行此函数时,它会在转到下一行之前等待循环完成,但由于我没有使用 await
,所以它不应该转到下一行吗?
谁能解释一下它在这里是如何工作的?以及如何避免等待循环完成?
(我是 JS 新手,为我的菜鸟问题道歉)
示例代码:
function promiseLoop() {
return new Promise(( resolve ) => {
Array(2000).fill(0).forEach(function() {
console.log("?running...")
})
console.log("✅")
return resolve(true);
})
}
async function withoutAwait() {
console.log("withoutAwait >>> I will run funcWithPromise")
promiseLoop()
console.log("withoutAwait >>> Done, funcWithPromise")
}
async function withAwait() {
console.log("withAwit >>> I will run funcWithPromise")
await promiseLoop()
console.log("withAwit >>> Done, funcWithPromise")
}
withoutAwait()
withAwait()