Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequential execution in node.js

Tags:

node.js

I have code like

common.findOne('list', {'listId': parseInt(request.params. istId)}, function(err, result){       
  if(err) {
    console.log(err);
  }
  else {
    var tArr = new Array();               
    if(result.tasks) {
      var tasks = result.tasks;
      for(var i in tasks) {
        console.log(tasks[i]);
        common.findOne('tasks', {'taskId':parseInt(tasks[i])}, function(err,res){
          tArr[i]  = res;       
          console.log(res);                     
        });                       
      }
      console.log(tArr);
    }               
    return response.send(result); 
  }
});

It is not executed sequentially in node.js so I get an empty array at the end of execution. Problem is it will first execute console.log(tArr); and then execute

common.findOne('tasks',{'taskId':parseInt(tasks[i])},function(err,res){
      tArr[i]  = res;       
      console.log(res);                                         
});                       

Is there any mistake in my code or any other way for doing this. Thanks!

like image 415
priyanka patel Avatar asked Mar 10 '12 05:03

priyanka patel


People also ask

Is JavaScript executed sequentially?

39.1. 2 JavaScript executes tasks sequentially in a single process. This loop is also called the event loop because events, such as clicking a mouse, add tasks to the queue.

What is Sequelize in node JS?

Sequelize is a Node. js-based Object Relational Mapper that makes it easy to work with MySQL, MariaDB, SQLite, PostgreSQL databases, and more. An Object Relational Mapper performs functions like handling database records by representing the data as objects.


1 Answers

As you are probably aware, things run asynchronously in node.js. So when you need to get things to run in a certain order you need to make use of a control library or basically implement it yourself.

I highly suggest you take a look at async, as it will easily allow you to do something like this:

var async = require('async');

// ..

if(result.tasks) {
  async.forEach(result.tasks, processEachTask, afterAllTasks);

  function processEachTask(task, callback) {
    console.log(task);
    common.findOne('tasks', {'taskId':parseInt(task)}, function(err,res) {
      tArr.push(res); // NOTE: Assuming order does not matter here
      console.log(res);
      callback(err);
    });
  }

  function afterAllTasks(err) {
    console.log(tArr);
  }
}

The main things to see here is that processEachTask gets called with each task, in parallel, so the order is not guaranteed. To mark that the task has been processed, you will call callback in the anonymous function from findOne. This allows you to do more async work in processEachTask but still manage to signify when it is done. When every task is done, it will then call afterAllTasks.

Take a look at async to see all the helper functions that it provides, it is very useful!

like image 134
staackuser2 Avatar answered Oct 23 '22 10:10

staackuser2