拒绝一个捆绑的承诺



angular文档说你可以把承诺链起来,像这样:

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

是否可能在函数内拒绝promiseB ?

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

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

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

这是有效的,因为promise的成功回调的返回值被转换为另一个承诺,这个承诺要么被成功回调的返回值解决,要么被拒绝,如果我们用$q.reject显式拒绝它或抛出异常。

实际上,.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文档

最新更新