【问题标题】:Promise chaining with success and reject functions带有成功和拒绝功能的承诺链
【发布时间】:2019-02-21 10:52:02
【问题描述】:

给定如下代码:

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 });

如果你想在解决或拒绝时返回一个承诺,那么你必须做些什么才能从这里返回一个承诺以启动一个链,看起来你最终会复制代码。是这种情况还是您可以采取一些措施来使此过程更清晰

【问题讨论】:

  • 只是不要从您的解析和拒绝处理程序中返回任何内容,然后在之后运行 NextPromise:p.then( func... , func... ).then( theNextPromise ).then( result => ...
  • @Paulpro Promise.prototype.then() 接受一个函数,而不是一个承诺,所以p.then(...).then(() => theNextPromise).then(result => ...) 是正确的答案。

标签: javascript es6-promise


【解决方案1】:

这个怎么样?你初始化 Promise 对象并继续链接,直到你想完成 Promise。

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) 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-25
    • 1970-01-01
    • 2013-09-16
    相关资源
    最近更新 更多