0

I am trying to create a loop where every iteration makes a request to Asana's API and the return value gets pushed into an array.

So for example

for(thing of totalThings){
 getAProject(some projectID)
 .then(function(getAProject's Response){
 someArray.push(getAProject's Response 
})
.catch();
}

I'd like to use someArray after this for loop finishes but I'm not sure where I should be placing my return statement.

Peter Kim
  • 25
  • 3

1 Answers1

1

Is the goal to iterate through a set of results (e.g. tasks) from the API page by page? And are you using the Asana JS client? If so, please see the Collections documentation for the library, which describes various ways to do this.

Otherwise, are you doing something different than that, like maybe trying to get info about a bunch of projects in parallel? Note that promise code is asynchronous, so if you'd like to use someArray at some point "after" the code finishes, you need to "wait" for all the promises to resolve.

Assuming that getAProject itself returns a promise, you might have something like:

var Promise = require('bluebird');
var responses = [];
for (...) {
  responses.push(getAProject(id));
}
Promise.all(responses).then(function(responses) {
  // Use the responses here
});
Greg S
  • 2,079
  • 1
  • 11
  • 10
  • Hi Greg your code actually worked. Right now however, this piece with the loop is already executing as part of a promise chain. So, right now it looks like doSomething().then().doSomethingElse().then(The for loop execution) Right now the results of the for loop can only be dealt with inside its own promise chain. Do you know how I would be able to return the results ot the outer promise chain? – Peter Kim Aug 01 '15 at 17:09
  • Yeah, just `return Promise.all(...)` instead. :) Does that make sense or do you need more detail? – Greg S Aug 02 '15 at 17:54