拒绝链式承诺

时间:2014-06-18 15:19:47

标签: javascript angularjs q

angular docs say你可以链接承诺,如下:

promiseB = promiseA.then(function(result) {
    return result + 1;
});

是否可以从函数中拒绝promiseB

promiseB = promiseA.then(function(result) {
    if (result > 0) {
        return result + 1;
    }
    else {
        // reject promiseB
    }
});

P.S。:在这个例子中,我假设promiseA总是解析。

2 个答案:

答案 0 :(得分:3)

promiseB = promiseA.then(function(result) {
    if (result > 0) {
        return result + 1;
    }
    else {
        return $q.reject('whatever reason');
    }
});

这正常工作将promiseA的成功回调的返回值转换为另一个promise,该promise使用成功回调的返回值解析,或者如果我们使用$q.reject显式拒绝它,则拒绝它或者抛出异常。

答案 1 :(得分:2)

事实上,你可以使用.then()函数获取两个回调函数。一个用于成功,一个用于同一文档中指定的错误。在错误处理程序回调中,您可以使用$ q.reject()来拒绝承诺。但是,话虽如此,您也可以在成功回调中使用它:

  promiseB = promiseA.then(function(result) {
    // success: do something and resolve promiseB
    //          with the old or a new result

    if (!result || result !== "Whatever you're looking for" ) { 
        $q.reject("A Reason")
    } // additional edit from me

    return result;
  }, function(reason) {
    // error: handle the error if possible and
    //        resolve promiseB with newPromiseOrValue,
    //        otherwise forward the rejection to promiseB
    if (canHandle(reason)) {
     // handle the error and recover
     return newPromiseOrValue;
    }
    return $q.reject(reason);
  });

* 取自Angular Documentation