似乎无法找到这样的循环是否非阻塞的答案。
let workComplete = false;
let itemFound = false;
Object.keys(myObject).forEach((key, index) => {
// check thousands of keys for a match
if(key === someOtherValue) {
itemFound = true;
}
if(index === Object.keys(myObject).length - 1) {
workComplete = true;
}
});
// Is it true that subsequent work here
// will not execute until the forEach completes?
console.log(workComplete);
保证上方的代码是否始终将对console.log()
的调用打印为workComplete
的{{1}}值?
答案 0 :(得分:1)
您提供的所有代码均同步执行。它将与第一个键同步运行您的功能,然后对第二个键进行相同的操作,依此类推,直到所有键用尽。只有这样,它才能注销COMPILE_DEFINITIONS
。
答案 1 :(得分:0)
您提供的代码将同步执行,部分原因是没有异步工作。如果您在forEach()
中调用异步函数,则不会被阻塞:
async function isThing(key) {
return await checkIfThing(key);
}
async function findThing() {
// forEach will not await isThing, so
// all calls will immediately after each other
Object.keys(Things).forEach(isThing);
// This syntax lets you do each await
for (var key of Object.keys(things) {
await isThing(key)
}
}
您可以利用Promise行为来发挥优势,例如并行执行一堆获取并在完成后解决:
async function getThing(name) {
return await fetch(`${url}/${name}`)
}
async function getAllThings() {
const thingPromises = Object.keys(Things).map(getThing);
const things = await Promise.all(thingPromises);
return things;
}