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!
staackuser2
source share