throw Error after promise is rejected - Q

℡╲_俬逩灬. 提交于 2019-12-01 11:33:12

All errors in then handlers are caught and used to reject the resulting promise. What you want is the done method:

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.

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.

Q.ninvoke(fs, "readfile", "foo.txt", "utf-8").done(function(data){
    console.log('all good');
}, function(err) {
    throw new Error('I want to throw this exception');
}); // or omit the error handler, and 'err' will be thrown
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!