承诺链接成功和拒绝功能

时间:2019-02-21 02:14:55

标签: javascript es6-promise

给出如下代码:

let p = somePromise
p.then(
    function (response) {
        $scope.resultDetails = response.data;
        return theNextPromise;
    },
    function (error) {
        $scope.resultDetails = error.data;
        return theNextPromise;
    }
).then((result) => { ...do more stuff here });

如果您想在解决或拒绝时返回一个承诺,那么从中返回一个承诺将需要做些什么,看来您最终将复制代码。是这种情况还是您可以采取一些措施使此过程更简洁

1 个答案:

答案 0 :(得分:0)

这个怎么样?您初始化诺言对象并保持链接,直到您要最终确定诺言为止。

let sequence = Promise.resolve()

sequence = sequence.then(() => {
  return p
});

sequence = sequence.then((response) => {
    $scope.resultDetails = response.data;
    return theNextPromise;
  },
(error) => {
    $scope.resultDetails = error.data;
    return theNextPromise;
  }));

sequence = sequence.then(result => {return promise object})

// finalize
sequence.then(do something)