gpt4 book ai didi

javascript - Promise 中的 .done 是什么?

转载 作者:行者123 更新时间:2023-11-28 13:10:26 25 4
gpt4 key购买 nike

我正在学习 JS Promise,我注意到一些使用 Promise 的代码示例是它们在末尾附加 .done 。我查过Promise api但找不到任何相关信息。我的假设是它的工作方式类似于 try...catch 语句中的finally,无论 Promise 返回什么,它都会被调用。我到处寻找但找不到答案。

所以我的问题是,它是内置在 Promise 中的吗?它基本上是做什么的?

跟进问题

如果 .done() 在 vanilla JS 中不存在,有没有办法模仿这个“catch-all”函数?

编辑

抱歉,这没有包含在 ES6 Promise 规范中,所以我删除了 ES6 标签。

最佳答案

一些 Promise 库有一个 .done() 方法,其主要目的是捕获并重新抛出任何未处理的错误,以便它们显示在控制台(在浏览器中)或崩溃Node 中的流程。我怀疑这就是为什么你经常在 promise 链的末尾看到它。

在 Q 和 bluebird 中,它接受已完成和拒绝处理程序,但由于它返回 undefined,因此无法进一步链接。 bluebird 文档不鼓励使用它,并表示它仅用于历史目的,因为 bluebird 提供了更优雅的方法来处理未处理的错误。

来自the Q documentation :

Much like then, but with different behavior around unhandled rejection. If there is an unhandled rejection, either because promise is rejected and no onRejected callback was provided, or because onFulfilled or onRejected threw an error or returned a rejected promise, the resulting rejection reason is thrown as an exception in a future turn of the event loop.

This method should be used to terminate chains of promises that will not be passed elsewhere. Since exceptions thrown in then callbacks are consumed and transformed into rejections, exceptions at the end of the chain are easy to accidentally, silently ignore. By arranging for the exception to be thrown in a future turn of the event loop, so that it won't be caught, it causes an onerror event on the browser window, or an uncaughtException event on Node.js's process object.

Exceptions thrown by done will have long stack traces, if Q.longStackSupport is set to true. If Q.onerror is set, exceptions will be delivered there instead of thrown in a future turn.

The Golden Rule of done vs. then usage is: either return your promise to someone else, or if the chain ends with you, call done to terminate it. Terminating with catch is not sufficient because the catch handler may itself throw an error.

回复:有没有办法模仿这个包罗万象的功能?

像下面这样的东西应该可以解决问题:

if (!Promise.prototype.done) {
Promise.prototype.done = function (onfulfilled, onrejected, onprogress) {
this.then(onfulfilled, onrejected, onprogress)
.catch(function (error) {
setTimeout(function () { throw error; }, 0);
});
};
}

关于javascript - Promise 中的 .done 是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42953447/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com