Search code examples
angular-promisebluebirdasana

How to create a loop where each iteration makes a request that returns a promise


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.


Solution

  • 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
    });