Sequential execution in node.js

I have a 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 does not execute sequentially in node.js, so I get an empty array at the end of execution. The problem is that 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 error in my code or any other way for this. Thank you

+7
source share
2 answers

As you probably know, everything works asynchronously in node.js. Therefore, when you need to make things work in a certain order, you need to use the management library or basically implement it yourself.

I highly recommend you take a look at async , as this 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 thing is to see here that processEachTask is called with each task in parallel, so the order is not guaranteed. To note that the task has been processed, you call callback in an anonymous function from findOne . This allows you to do more asynchronous work in processEachTask , but you can still determine when it will be done. When each task is completed, it will call afterAllTasks .

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

+13
source

I recently created a simple abstraction called " wait.for " to call asynchronous functions in synchronization mode (based on Fibers): https://github.com/luciotato/waitfor

Using wait.for and async:

 var wait = require('waitfor'); ... //execute in a fiber function handleRequest(request,response){ try{ ... var result = wait.for(common.findOne,'list',{'listId': parseInt(request.params.istId)}); var tArr = new Array(); if(result.tasks) { var tasks = result.tasks; for(var i in tasks){ console.log(tasks[i]); var res=wait.for(common.findOne,'tasks',{'taskId':parseInt(tasks[i])}); tArr[i] = res; console.log(res); } console.log(tArr); return response.send(result); }; .... } catch(err){ // handle errors return response.end(err.message); } }; // express framework app.get('/posts', function(req, res) { // handle request in a Fiber, keep node spinning wait.launchFiber(handleRequest,req,res); }); 
+5
source

All Articles