如何使用.map()将promise的结果分配给数组元素? [英] How to assign the result of a promise to array elements using .map()?

查看:108
本文介绍了如何使用.map()将promise的结果分配给数组元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里使用AngularJS,但是如果您有更通用的答案,我将很高兴知道.

I am using AngularJS here, but if you have a more generic answer I’ll be glad to know about it.

我有一个包含ID的元素数组

I have an array of elements containing ids

myArray = [{
  id: 0,
  foo: "foo"
}, {
  id: 1,
  bar: "bar"
}]

还有一个使用这些ID询问信息的服务,该ID以一个信息对象(用于请求)和两个回调(一个用于成功,一个用于错误(都不是必需的))作为参数.

And a service to ask informations using those ids, which take as arguments an object of informations (for the request), and two callbacks, one for success and one for error (both are not required).

Service.getInformations({id: 1}, onSuccess, onError)

我想做的是这样的:

myArray.map(function (element){
  Service.getInformations({id: element.id}, function(data) {
    return data; // here is the issue
  })
});

这里的问题是我在服务回调函数中而不是在地图回调函数中返回数据.我正在努力寻找一些好的方法.

The issue here is that I am returning data in service callback function and not in map callback function. I am struggling to find some good way to do it.

推荐答案

Promise.all(myArray.map(item => new Promise((resolve, reject) => {
  Service.getInformations({id: item.id}, resolve, reject)
}).then((resultArray) => {
  //reduce result
}).catch((errorArray)=> {
  //reduce error
})

这篇关于如何使用.map()将promise的结果分配给数组元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆