javascriptnode.jscheerio

a way to know when all callbacks are done in javascript


I have many calls to a service at the end of which i want to write to a file my final collection when all the callbacks of the service have returned. is there there a way to be sure that all callbacks are done ?

for (id in idsCollection) {
    object.callService(id, function (res) {
        collection.push(res);
    });
}

filewriter.writetoFile("filename.json", JSon.Stringify(collection));

EDIT : just for the record i'm using cheerio with nodeJS.


Solution

  • Create an array. Push something onto the array each time you set up a callback. Pop something off it each time the callback runs. Check to see if the array is empty inside the callback function. If it is empty, then all the callbacks are done.