node.js - TypeScript 等待 Promise.all 并返回结果

标签 node.js typescript promise async-await

我正在 Node.Js 中编写一些代码,并使用 Promise.all 进行并行执行。为了简化问题,我使用以下示例代码

在 MyService.ts 中

@Injectable()
export class MyService {
    constructor(private readonly anotherService: AnotherService) { }

    public async job1(a: number): Promise<MyObject> {
        // try to calculate the result in parallel.
        const promiseArray = [];
        promiseArray.push(this.anotherService.job2(a));
        promiseArray.push(this.anotherService.job2(a + 1));
        promiseArray.push(this.anotherService.job2(a - 1));

        await Promise.all(promiseArray).then((results: MyObject[]) => {
            for (const obj of results) {
                if (obj.Index === 1) {
                    return obj;
                }
            }
        });

        return null;
    }
}

anotherService.job2()返回类型 Promise<MyObject> .

我准备好了测试数据,将断点设置为return obj;return null; ,它首先停在 return obj;然后在return null; 。因此这个函数的调用者得到 null最终。

如果我将代码更改为

@Injectable()
export class MyService {
    constructor(private readonly anotherService: AnotherService) { }

    public async job1(a: number): Promise<MyObject> {
        // try to calculate the result in parallel.
        const promiseArray = [];
        promiseArray.push(this.anotherService.job2(a));
        promiseArray.push(this.anotherService.job2(a + 1));
        promiseArray.push(this.anotherService.job2(a - 1));

        const results = await Promise.all(promiseArray);
        for (const obj of results) {
            if (obj.Index === 1) {
                return obj;
            }
        }

        return null;
    }
}

它有效。

正确的使用方法是什么 Promise.all并返回结果?我什么时候应该使用 Promise.all().then()

最佳答案

代码第一个版本的问题是您只为 job1 函数返回 null

你可以像这样重写,注意我们返回的是then的结果:

...
        return await Promise.all(promiseArray).then((results: MyObject[]) => {
            for (const obj of results) {
                if (obj.Index === 1) {
                    return obj;
                }
            }

            return null;
        });
...

回答你的问题,什么时候使用什么。我认为这取决于您发现的两种方法中哪一种最简单、最容易阅读和维护。

我个人更喜欢你的第二种方法。

关于node.js - TypeScript 等待 Promise.all 并返回结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54413274/

相关文章:

typescript - 函数重载错误 : TS7006:Parameter 'x' implicitly has an 'any' type

javascript - Node.js exec 事件未在 Promise 内触发

Javascript Promise.all - 如何使这个现有功能同步?

node.js - 如何在 Nodejs 代理服务器上查询请求?

node.js - 如何返回 mongoDB 数组中值的最大出现次数

node.js - 如何使用 Node js获取特定值

javascript - 有前途的听众

javascript - 加入 mongoDB

typescript - 子组件事件广播给父组件

class - 在 TypeScript 中声明动态添加的类属性