Search code examples
javascripthttpasynchronouspromisersvp.js

Javascript Asynchronous Function Chaining


I have a set of JavaScript functions on a Node server that are making HTTP requests to an external API. I'm trying to chain them. My HTTP request function returns a promise, so I've been trying to utilize .then().

var x = function(id){
    //Passes a URL and the ID provided and returns a promise
    return callAPI(url, id)
}

var y = function(id){
    //Same deal. Different URL, but calls a URL with an ID and returns a promise.
    return allAPI(url, id)
}

var z = function(id){
   var result = [];
   x(id).then(function(data){
       var promises = data.body.ids.map(function(id){
          return y(id);
       });
       RSVP.all(promises).then(function(){
          console.log('Promises finished') //this never runs
       });
   });
}

I read that forEach is synchronous, but if you're doing async things in the forEach there is no guarantee it will return correctly. I think that the result array is being populated, I am just returning it at the wrong time? But I am not sure where/how I can return it after all the promises have been fulfilled. Thoughts?

edit Adding the function that creates the promises. Maybe I'm doing that wrong?

var callAPI = function(url, query){
    var promise = new RSVP.Promise(function(resolve, reject){
        su.get(url)
            .query(query)
            .on('error', function(){
                reject(this);
            })
            .end(function(res){
                resolve(res);
            });
    });
    return promise;
}

This uses the SuperAgent HTTP framework. If I do a console.log on the returned promise, everything about it is undefined? But the functions that use callAPI still work? And I can chain them with .then still? Maybe I've missed something.


Solution

  • I removed RSVP and used Bluebird instead. For whatever reason, RSVP.all() was never firing even when all of the promises were fulfilled. I switched to Bluebird and everything worked as expected.