我正在 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/