0

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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
thisisnotabus
  • 1,949
  • 3
  • 15
  • 31
  • `return Promise.all(result)` and `return` the `.then` chain so you can hook on it later. – Benjamin Gruenbaum Feb 18 '15 at 16:16
  • I added the callAPI definition that returns the promise. Any idea if I'm doing that incorrectly? If I create an array of promises and then use RSVP.all(promises), the .then never runs. Thoughts? – thisisnotabus Feb 18 '15 at 19:33
  • Hm, no, that should work. Maybe one of the promises is rejected? – Bergi Feb 18 '15 at 19:36
  • So, fun tip: RSVP was the problem. I switched out RSVP with Bluebird and everything worked perfectly. I didn't even have to change any syntax (aside from anywhere I referenced RSVP). This was weird. – thisisnotabus Feb 21 '15 at 15:23

1 Answers1

0

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.

thisisnotabus
  • 1,949
  • 3
  • 15
  • 31
  • In that case, you should open an issue at RSVP, and include a complete reproducible example in your bug report. – Bergi Feb 21 '15 at 17:29