【发布时间】:2021-01-23 07:01:02
【问题描述】:
我有以下代码,其中我遍历了一个包含名称的列表,并在这种情况下使用每个名称来获取相应的房子。这很好用,但我想将所有承诺包含在Promise.all() 中 - 如何将每个名称的承诺动态添加到Promise.all()?这里有什么好的做法?
list = [
'Name1',
'Name2',
'Name3'
];
this.houses = new BehaviorSubject<any>([]);
const promises = this.greatHouses.map(name => {
let house;
return this.fetchHouse(name).then((result: any[]) => {
house = result[0];
return result[0];
}).then((result: any) => {
return this.fetchLord(result.currentLord);
}).then((result: any) => {
const currentLord = Characters.default.find(char => char.characterName === result.name);
return [{...house, currentLord}];
});
});
Promise.all(promises).then(values => {
console.log(values);
});
fetchHouse(name: string) {
return this.http.get(`${this.housesUrl}`, {
params: {
name
}
}).toPromise();
}
fetchLord(url: string) {
return this.http.get(url).toPromise();
}
【问题讨论】:
-
只收集你在数组中创建的承诺,然后调用
Promise.all?最佳做法是为此使用map而不是list数组上的循环,但两者都可以。 -
个人而言,我会使用
this.list.map和return this.fetchHouse .... etc然后返回的数组可以与 Promise.all 一起使用 -
顺便说一句,关于
let house,还有更好的ways to access previous promise results in a .then() chain。 -
别忘了在最后加上
.catch(console.error)。您更新的问题中的代码应该可以工作。 -
你的单个 promise 也一样,只是你从来没有注意到它,因为你根本没有处理错误。
标签: javascript angular typescript promise rxjs