0

A simplified version of my problem:

var request = require('request');

var myJSONObject;
request.get(largeEndpointThatOnlyHasIDs, {authstuff}, function (err, response, body) {
    if (!err && response.statusCode = 200) {
        JSON.parse(body).forEach(function(item) {
            getItemData(item.item_id, function(result) {
                myJSONObject['itemData'] = result;
            });
        });
    }
});

getItemData(id, callback) {
    request(itemAPIEndpoint, function(err, response, body) {
        if (!err && response.statusCode = 200) {
            callback(JSON.parse(body));
        }
    });
}

Alright, so that kind of works. I can console.log(myJSONObject) inside the callback just fine and see that it's populating it one at a time. Basically I just can't figure out how to wait until the entire forEach has finished, myJSONObject is populated and I can use it for other things.

Sorry, I'm not really sure if I'm explaining what I mean very well. If not, let me know and I will try to clarify a bit more.

Keirathi
  • 397
  • 1
  • 5
  • 18
  • 1
    This question has been asked many times (I've answered it several times myself). You can use a counter to count when all the async operations are done or you can use `Promise.all()` with promises or you can use the async library. There are many dups to this. I will go see if I can find one. – jfriend00 Mar 09 '16 at 22:32
  • Something similar using jQuery: http://stackoverflow.com/questions/24484601/how-to-use-promise-done-on-each-json-array-when-done-completed/24484713#24484713 – jfriend00 Mar 09 '16 at 22:33
  • Typed something up in two minutes -> **https://jsfiddle.net/fkbe4mhs/** – adeneo Mar 09 '16 at 22:36

0 Answers0