node.js 中的顺序执行 [英] Sequential execution in node.js

查看:76
本文介绍了node.js 中的顺序执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有像

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); 
  }
});

它不是在 node.js 中按顺序执行的,所以我在执行结束时得到一个空数组.问题是它会先执行 console.log(tArr); 然后再执行

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!

推荐答案

您可能知道,node.js 中的事情是异步运行的.因此,当您需要按照特定顺序运行时,您需要使用控制库或基本上自己实现.

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.

我强烈建议您查看 async,因为它可以轻松让您执行类似的操作这个:

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);
  }
}

这里的主要内容是 processEachTask 与每个任务并行调用,因此无法保证顺序.要标记任务已处理,您将在 findOne 的匿名函数中调用 callback.这允许您在 processEachTask 中做更多的异步工作,但仍然设法在完成时表示.当每个任务完成后,它会调用afterAllTask​​s.

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.

看一看async,看看它提供的所有辅助功能,非常有用!

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

这篇关于node.js 中的顺序执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆