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

时间:2014-03-05 12:49:55

标签: javascript node.js promise q

以下是使用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中抛出异常以防止承诺被拒绝(或者在某些情况下它被解析)。无论如何,异常被忽略,程序结束而不抛出异常。

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

谢谢

1 个答案:

答案 0 :(得分:9)

then处理程序中的所有错误都被捕获并用于拒绝生成的承诺。你想要的是done method

  

很像then,但在未处理的情况下有不同的行为   拒绝。如果有未处理的拒绝,要么是因为   promise被拒绝,并且未提供onRejected回调,或   因为onFulfilledonRejected投掷错误或返回了   拒绝承诺,由此产生的拒绝理由被抛弃   事件循环的未来转向中的异常。

     

此方法应该用于终止承诺链   不能在别处传递。由于在then回调中引发了异常   消费并转化为拒绝,最后例外   链条很容易被意外,默默地忽略。通过安排   在事件循环的未来转向中抛出的异常,以便   它不会被捕获,它会在浏览器上导致onerror事件   Node.js window上的uncaughtExceptionprocess事件   对象

     

donethen用法的黄金法则是:return你的。done   向其他人承诺,或者如果链条以您结束,请致电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   终止它。

{{1}}
相关问题