【问题标题】:How to simply change q.js-promise 'errormessage' on reject?如何在拒绝时简单地更改 a.js-promise '错误消息'?
【发布时间】:2013-05-24 11:58:51
【问题描述】:

我使用Q.js 来表示承诺。

我想知道当 Q-promise 失败时是否可以快速格式化/更改错误消息。

考虑一个人为的例子:

           return Q.when(//$.ajaxpromise for instance).then(function(result){
                    //handle result
                }).fail(function(err){
                    //somehow change err (returned from $.ajax) to something
                    //sensible (say the statuscode + responseText) and
                    //push it up the callstack
                });

当然我可以做以下事情,但感觉有点麻烦:

             var deferred = Q.defer(); 
             Q.when( //$.ajaxpromise for instance).then(function(result){
                    //handle result
                    deferred.resolve();
                }).fail(function(err){
                    deferred.reject(new Error(err.responseText));
                });
             return deferred.promise;

无论如何要更优雅地做到这一点?

【问题讨论】:

    标签: asynchronous promise q


    【解决方案1】:

    Q Promise(以及任何 Promises/A+ 实现)的美妙之处在于,您只需 throw

    return Q.when(otherPromise)
        .then(function (result) { /* handle result */ })
        .fail(function (err) { throw new Error('A real error!'); });
    

    您可以在"Propagation" section of the Q readme 中找到此信息。

    【讨论】:

    • true,但是当whenthen 包含异步代码时,调用堆栈的任何尝试/捕获都无法捕获抛出的错误。但是他,这不是问题的一部分,而且我已经让东西运行稳定了,所以这是你的选择:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-27
    • 2013-10-16
    • 1970-01-01
    • 2021-04-21
    • 2016-05-18
    • 2012-11-08
    • 1970-01-01
    相关资源
    最近更新 更多