javascript - 地图请求完成时解决承诺
问题描述
我正在处理书签页面,我们得到带有书签的餐厅 ID 的书签结果。然后我映射响应并将其作为对象推送到数组。
我想解析整个完成的数组,以便之后可以操作数据。
我创建了一个 getData 函数,它向书签 api 发出请求,在 onSucces 中我调用了一个名为 mapResult 的函数,如下所示:
mapResults(result: Array<any>, type: string): Promise<any> {
const promise = new Promise<any>((resolve, reject) => {
const requests = result.map((res, i) => {
this.getRestaurantById(res.RestaurantId).then(restaurant => {
const bookmarks = {
createdDate: res.CreatedDate,
restaurant: restaurant[0]
};
this.savedData[type].push(bookmarks);
});
});
Promise.all(requests).then((completed) => {
if(completed) {
console.log(completed)
resolve(this.savedData[type]);
}
})
});
return promise;
}
我订阅的地方是这样的:
this.mapResults(result, type).then(data => {
console.log(data)
});
但是data
console.log 不是整个数据数组,它只会解析第一个对象。
为什么Promis.all
函数不等待地图完成?
解决方案
您的代码中有几个问题:
- 你
return
在result.map
回调中什么都没有 new Promise
没有必要- 您不应该使用状态变量而不是承诺返回值
- 变量
completed
没有任何意义
此代码应按预期工作:
mapResults(result: Array<any>, type: string): Promise<any> {
// you don't need "new Promise" as "getRestaurantById" already returns a promise itself
const requests = result.map((res) => {
// here you forgot to return something
return this.getRestaurantById(res.RestaurantId).then(restaurant => {
return {
createdDate: res.CreatedDate,
restaurant: restaurant[0]
};
});
});
// using "completed" did not make any sense as it is just an array filled with "undefined"s
return Promise.all(requests).then((restaurants) => {
console.log(restaurants)
// TODO store "restaurants" in "this.savedData[type]" if needed
return restaurants;
});
}
推荐阅读
- angular - Angular 9 - 解析给定网址的每个参数
- elasticsearch - 尝试过滤该字段可能不存在的一些 Elasticsearch 结果
- python - 如何修复 langdetect 不稳定的结果
- javascript - 节点:使用 promise.all() 来并行调用 API?
- ios - 如何使用 Rx 在 tableView 中使用多个单元格?
- python - 蟒蛇 | 使用套接字连接到远程服务器
- regex - 在查询中使用通配符重写条件
- javascript - 如何开玩笑地模拟回调?
- postgresql - Postgres - 仅选择列值更改的行
- spring - DatasSourceBuilder 与 DriverManagerDataSource