通过承诺链传递变量 [英] Passing Variables Through a Promise Chain

查看:64
本文介绍了通过承诺链传递变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有更好的方法吗?

let foo;
return functionA().then(result => {
  foo = result;
  return functionB();
}).then(bar => {
  return functionC(foo, bar);
});

请注意, functionA 的结果是必需的输入 functionC 。使用promise范围之外的变量工作正常,但感觉有点icky。有没有一个干净的惯用方法呢?

Notice that the result of functionA is required input to functionC. Using a variable outside the promise scope works fine, but it feels kinda icky. Is there a clean idiomatic way to do this?

请注意,我没有机会更改我正在调用的任何函数的API。

Please note that I do not have the opportunity to change the API of any of the functions I am calling.

推荐答案

您可以尝试使用 Promise.all() 你可以传递一组promises并提供一个数组当传入的所有承诺都已解决时, then()回调内的响应。您可以访问这些数组值以传递到 functionC

You could try using Promise.all() which you can pass an array of promises and it provides an array of responses within the then() callback when all promises passed in have resolved. You can access those array values to pass into functionC:

Promise.all([functionA, functionB]).then(values => functionC(values[0], values[1]));

可能会更清洁(没有嵌套),因为它看起来不像 functionA 需要传递到 functionB

Might be a little cleaner (without nesting) as it doesn't look like the response from functionA needs to be passed into functionB.

否则,嵌套看起来像是:

Otherwise, nesting would look like:

return functionA().then(foo => {
    return functionB().then(bar => {
        return functionC(foo, bar);
    });
});

希望有所帮助。

这篇关于通过承诺链传递变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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