[英]How to preserve Typescript return types when calling Promise.all?
[英]TypeScript wait for promise.all and return result
我正在 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 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
返回结果的正确方法是什么? 我什么时候应该使用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;
});
...
回答你的问题,什么时候用什么。 我认为这归结为您找到的两种方法中最简单、最易于阅读和维护的方法。
我个人更喜欢你的第二种方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.