微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 承诺被拒绝后抛出错误 – 问:

以下是使用Q的承诺的简短示例.

这是test1.js:

function testDefer() {
    var deferred = Q.defer();
    fs.readFile("foo.txt", "utf-8", function (error, text) {
        if (error) {
            deferred.reject(new Error(error));
        } else {
            deferred.resolve(text);
        }
    });
    return deferred.promise;
}

这是test2.js

(function(){
    'use strict';
    var test1 = require('./test1');
    test1.testDefer().then(
        function(data){
            console.log('all good');
        },
        function(err) {
            //upon error i might want to throw an exception, however, it is not thrown / ignored.
            throw new Error('I want to throw this exception');
        }
    );
})();

我想在test2中抛出异常,以防止承诺被拒绝(或者在某些情况下它被解决).无论如何,异常被忽略,程序完成而不抛出异常.

我的问题是,如何从成功/失败函数中抛出错误

谢谢

解决方法:

处理器中的所有错误都被捕获并用于拒绝生成的承诺.你想要的是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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐