我很难理解与处理 Promise 的情况有何for...of不同。.forEach()
使用这个片段:
const allSettled = async arr => {
    const data = []
    for (const promise of arr) {
        try {
            const result = await promise;
            data.push(result);
        } catch (e) {
            data.push(e)
        }
    }
    return data
}
我检查数组中的每个承诺,等待它解决并将结果推送到data. 它按顺序执行。
如果我有这个片段:
const badAllSettled = arr => {
    const data = []
    arr.forEach(async promise => {
        try {
            const result = await promise;
            data.push(result);
        } catch (e) {
            data.push(e)
        }
    })
    return data
}
我得到空数组(因为forEach不等待 Promise 解决)。
AFAIKfor...of使用可迭代,因此它可能会挂起并等待await返回。但我不明白这个流程是如何一步步进行的。
谢谢!
.forEach()是这样实现的:
Array.prototype.forEach = function forEach(fn) {
  for (let i = 0; i < this.length; i++)
    fn(this[i], i, this);
}
正如你所看到的,当.forEach()调用时,它只是同步调用回调几次。但是,如果回调是异步函数,则不会等待它。
相比之下,当await在异步函数内找到关键字时,该函数中的所有代码执行都会暂停,直到 Promise 解决为止,这意味着任何控制流(包括for ... of循环)也会暂停。
以下代码的行为类似.forEach(),因为它调用等待 Promise 的异步函数,而不等待函数返回的 Promise:
const allSettled = async arr => {
    const data = []
    for (const promise of arr) {
        (async () => {
            try {
                 const result = await promise;
                 data.push(result);
            } catch (e) {
                data.push(e)
            }
        )();
    }
    return data
}