首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >承诺的v8闭包源代码中关于注释的问题

承诺的v8闭包源代码中关于注释的问题
EN

Stack Overflow用户
提问于 2020-08-03 15:12:24
回答 1查看 837关注 0票数 1

我只是看了一下v8编译器,特别是所有元素中的行,the :我碰到了这些行。

代码语言:javascript
复制
    // 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?问题出在哪里?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-08-03 15:16:57

--我不太明白Promise.allSettled怎么可能在同一元素上多次调用reject?

Promise.allSettled根本不给他们打电话。创建和解决承诺的代码确实做到了--并且可以不止一次地调用它们。因此,Promise.allSettled只是通过从您看到注释的函数的早期返回来处理这种情况。如果它还没有看到在该指数下的承诺的解决方案,它会继续,这样它就可以填充它正在填充的数组中的方式。

下面是一个函数的例子,A)调用reject一次,或者B)至少调用resolve一次(可能不止一次),同时也调用reject

代码语言:javascript
复制
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的line事件,检查给定文本的行,如果找到,则调用resolve--即使它以前已经被称为resolve。类似地,当它到达流的末尾时,它会调用reject,即使它以前被称为resolve。这没关系(尽管在我看来,可怜),因为一旦您完成了承诺,您就不能再次解决它;随后对resolvereject的调用将被忽略。

可悲的是,我在野外看到了代码就像这样的

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63232089

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档