在承诺链中返回多个值的最佳方式是什么 [英] What's the best way to return multiple values in a promise chain

查看:26
本文介绍了在承诺链中返回多个值的最佳方式是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确实意识到,在.Then()处理程序中返回非Promise时,它会立即传递到下一个处理程序,如果返回的是Promise,则在将其传递到下一个处理程序之前,会暂停执行以解析承诺。

我还知道承诺只能返回一个值。

蜜蜂说,我该如何着手将多个参数从一个.Then()处理程序返回到下一个处理程序?特别是如果它是承诺和非承诺的混合。目前,我将所有内容都放入一个自定义对象中,返回它,并在下面的Then()处理程序中使用异步等待,以便重新解析承诺。

然后使用已解析的承诺值和非承诺值一起执行某些工作。

这工作得很好,但我的直觉告诉我,不知何故,这不是它应该是的方式……也许?

示例:

const current = 'blah';
const previous = 'blubb';

this.doSomeAsyncWork()
.then(
    result => {
        const nonPromiseValue = new domSomethingSynchronous(current, previous);
        // "custom object, mix of promises and non-promises"
        return {
            nonPromise: nonPromise,
            promiseA: ControllerA.asyncOperationA(current, nonPromiseValue.someProperty),
            promiseB: ControllerB.asyncOperationB(nonPromiseValue.someOtherProperty),
        }
    }
)
.then(
    async x => {
        const nonPromiseValue = x.nonPromiseValue;
        const valueA = await x.promiseA;
        const valueB = await x.promiseB;

        // do something with the results of those three variables

    }
)
.catch(
    // ...
)

推荐答案

在一个.then末尾的承诺和非承诺数组上使用return Promise.all,可以在下一个.then中立即解构结果,不需要await也不需要async

阵列中的所有Promises都已解析后,Promise.all将解析。传递给它的未承诺将仅传递给下一个.then

const makeProm = () => new Promise(resolve => setTimeout(resolve, 1000, 'resolveValue'));

Promise.resolve()
  .then(() => {
    const prom = makeProm();
    const otherValue = 'foo';
    return Promise.all([prom, otherValue]);
  })
  .then(([resolveValue, otherValue]) => {
    console.log(resolveValue, otherValue);
  });

这篇关于在承诺链中返回多个值的最佳方式是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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