inhaler inhaler - 1 month ago 4
AngularJS Question

resolving a promise in a loop

i am having trouble with how to resolve and pass data back from a chained promise. I am using node js, with request-promise. Here is my code

start(name)
.then(firstFunction)
.then(secondFuntion)
.then(function(){
// i want to return data from secondfunction back
))


the problem is in secondFunction i have a for loop that performs a call on each object i got from firstFunction, which is an array of objects. do i resolve the promise after each iteration or after all iterations. Would it be smarter to creat a global object and save the result into that and return that result? my code for secondFunction looks like this

var secondFunction = function(data){
var promise = new Promise(function(){
for(var i= 0; i <data.length; i ++){
options = { url: "", jason: true}
rp.(options)
.then(function(resp){
// i do something with respose and need to save this
//should i resolve the promise here??
})
.catch(function(err){
});
}
});
return promise;
}


EDIT

i figured it out! Thanks for all the help, in my second function i did this

var task = function(item){
// performed the task in here
}

var actions = data.map(task);
return Promise.all(actions);

Answer

The normal pattern for performing an async action on each item in an array, is to make the action into a function that returns a Promise, you then use [].map() to map the array of values, into an array of Promises. You then use Promise.all(), that takes an array of Promises, and returns a single Promise that resolves with an array of values, when all the Promises in the original array are resolved. It looks like this:

var secondFunction = function(data) {
  var promisesArray = data.map(rp);
  return Promise.all(promisesArray);
}

Your third .then() will have an array of values resolved from applying rp on each of the items in data, in the order they appeared in data.

A shorter version with some ES6 sugar is:

const secondFunction = data => Promise.all(data.map(rp));

If you're using Bluebird, which is the de-facto promise library for server-side JS, you can use the shorthand, Promise.map(), which accepts an array and a mapping function, and does the same:

const secondFunction = data => Promise.map(data, rp);