如何在链的后期获取承诺的结果 [英] How to access results of a promise at a later part of a chain

查看:67
本文介绍了如何在链的后期获取承诺的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的承诺链

I have a promise chain like so

functionOne()
.catch(errorHandlerOne)
.then(functionTwo)        // calls functionTwo(responseOne)
.catch(errorHandlerTwo)
.then(functionThree)      // calls functionThree(responseTwo)
.catch(errorHandlerThree)
.finally(finalHandler)

这似乎是一个显而易见的答案,但是我的问题是:

This might seem to be an obvious answer, but my question is this:

我可以在 functionTwo()中访问 responseOne ,但是如何在 functionThree中访问 responseOne () finalHandler()?

I can access the responseOne in functionTwo() fine, but how can I access the responseOne in functionThree() or finalHandler()?

我曾考虑过将其分配给一个变量,然后再访问它,但它似乎很hacky,并且与promise链的流程背道而驰.我正在寻找更好的方法

I thought about assigning it to a variable and accessing it later, but it seems to be quite hacky and against the flow of the promise chain. I'm looking for a better way

推荐答案

如何在functionThree()或finalHandler()中访问responseOne?

how can I access the responseOne in functionThree() or finalHandler()?

通过某种方式将它们向前传递,作为 then 回调的返回值(或它返回的promise的分辨率值,实际上是同一件事).

By passing them forward in some way, as the return value of the then callback (or the resolution value of a promise it returns, which is effectively the same thing).

示例:

function asyncOp(name) {
  return new Promise(resolve => {
    resolve(name);
  });
}
asyncOp("one")
  .then(result1 => {
    return asyncOp("two")
      .then(result2 => [result1, result2]);
  })
  .then(results => {
    console.log("results", results);
  });

像这样的数组只是一个选择.您可以使用一个对象,也可以将中间结果存储在处理程序关闭的变量中,...

An array like that is just one option; you could use an object, you could store the interim results in variables the handler close over, ...

ES5中的相同示例(以防万一有人需要它):

Same example in ES5 (just in case someone needs it):

function asyncOp(name) {
  return new Promise(function(resolve) {
    resolve(name);
  });
}
asyncOp("one")
  .then(function(result1) {
    return asyncOp("two")
      .then(function(result2) {
        return [result1, result2];
      });
  })
  .then(function(results) {
    console.log("results", results);
  });

这篇关于如何在链的后期获取承诺的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆