Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js: How do you handle callbacks in a loop?

I'm using Node.js and Box SDK. My (failing!) code looks like this:

var connection = box.getConnection(req.user.login);
connection.ready(function () {
  connection.getFolderItems(0, null, function (err, result) {
    if (err) {
      opts.body = err;
    } else {
      opts.body = result;
      var a = [];
      for (var i=0; i < result.entries.length; i++) {
        connection.getFileInfo(result.entries[i].id, function (err, fileInfo) {
        if (err) {
          opts.body = err;
        } else {
          a.push(fileInfo);
        }
      });}
    }

In "procedural" terms, this is which I'm trying to do:

var connection= box.getConnection()
var items = connection.getFolderItems()
var itemList = new List
foreach (item in items) {
  connection.getFileInfo(item.id)
  itemList.add(item)
}
display(itemList)

My problem is that connection.getFolderItems() and connection.getFileInfo() are asynchronous - the "for" loop exits before all the results are returned.

Q: What is the best way in Node.js to 1) get the result of the first async call, 2) iterate through the list, making more async calls, and 3) process the results when everything is "done".

Q: Are promises a good choice here?

Q: Is done()/next() an option?

Q: Is there any "standard idiom" in Node.js for this kind of scenario?

like image 865
paulsm4 Avatar asked Apr 27 '16 02:04

paulsm4


People also ask

How many callbacks can respond to any event in NodeJS?

It will return the max listeners value set by setMaxListeners() or default value 10. By default, a maximum of 10 listeners can be registered for any single event.

How are callbacks invoked?

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action. The above example is a synchronous callback, as it is executed immediately.

How do callbacks work in NodeJS?

js Callback Concept. A callback is a function which is called when a task is completed, thus helps in preventing any kind of blocking and a callback function allows other code to run in the meantime. Callback is called when task get completed and is asynchronous equivalent for a function.


1 Answers

Promises are a great idea, but you may want to take a look at the async module, specifically the collection handlers. It allows you to run async calls against a list of 'things' and gives you a place to run a method when all of the async calls are done. Don't know if this is better than promises, but options are always nice.

// Should give you a rough idea
async.each(items, function (item, callback) {
  connection.getFileInfo(result, callback);
}, function (err) {
  console.log('All done');
});

https://github.com/caolan/async#each

like image 185
skarface Avatar answered Oct 23 '22 03:10

skarface