v8 closures of promises 关于源代码注释的问题

v8 closures of promises questions on comment in source code

只是在查看 v8 编译器,特别是 promise-all-element-closure.tq 中的行:我遇到了这些行。

    // Promise.allSettled, for each input element, has both a resolve and a
    // reject closure that share an [[AlreadyCalled]] boolean. That is, the
    // input element can only be settled once: after resolve is called, reject
    // returns early, and vice versa. Using {function}'s context as the marker
    // only tracks per-closure instead of per-element. When the second
    // resolve/reject closure is called on the same index, values.object[index]
    // will already exist and will not be the hole value. In that case, return
    // early. Everything up to this point is not yet observable to user code.
    // This is not a problem for Promise.all since Promise.all has a single
    // resolve closure (no reject) per element.

这个接缝就像一个错误修复。我不太明白 Promise.allSettled 怎么可能对同一个元素多次调用 resolve reject?出了什么问题?

I don't quite understand how Promise.allSettled would possibly call resolve reject on the same element more then once?

Promise.allSettled 根本不调用它们。创建和解决 promise 的代码确实如此——并且可以多次调用它们。所以 Promise.allSettled 只是通过从您看到该评论的函数中提前返回来处理这种情况。如果它没有看到该索引处的承诺的解决方案,它会继续,以便它可以填充 how它正在填充的数组。

这是一个函数示例,它要么 A) 调用 reject 一次,要么 B) 调用 resolve 至少一次(可能不止一次)并且还调用 reject

function findMatchInStream(stream, text) {
    return new Promise((resolve, reject) => {
        stream.on("line", line => {
            if (line.includes(text)) {
                resolve(line);
            }
        });
        stream.on("end", () => reject());
    });
}

该代码通过检查给定文本的行来响应 Node.js-like line 事件,如果找到,则调用 resolve - 即使它已经被调用 resolve 之前。同样,当它到达流的末尾时,它会调用 reject,即使它之前调用过 resolve。没关系(虽然在我看来,可怜)因为一旦你兑现了诺言,你就不能再兑现了;随后对 resolvereject 的调用将被忽略。

遗憾的是,我在野外见过这样的代码只是