Ulysse BN Ulysse BN - 7 months ago 33
AngularJS Question

How to assign the result of a promise to array elements using .map()?

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

I have an array of elements containing ids

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

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)

What I would like to do is something like this:

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