inhaler inhaler - 1 year ago 58
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

// 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}
// i do something with respose and need to save this
//should i resolve the promise here??
return promise;


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 =;
return Promise.all(actions);

Answer Source

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 =;
  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(;

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

const secondFunction = data =>, rp);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download