简体   繁体   English

如何理解节点中的回调和async.parallel

[英]how to understand callbacks and async.parallel in node

I'm very new to JavaScript and callbacks, so my apologies if this is a stupid question. 我对JavaScript和回调都很陌生,所以如果这是一个愚蠢的问题我很抱歉。 Based on the async docs for parallel , I came up with this example code that executed the expected way based on the docs: 基于并行异步文档 ,我想出了基于文档执行预期方式的示例代码:

async = require('async')

async.parallel([
    function(callback){
        setTimeout(function(){
          callback(null, 'one');
        }, 800);
    },
    function(callback){
      setTimeout(function(){
        callback(null, 'two');
      }, 100);
    }
],
    function(err, results){
      console.log(results)
    })       

Running this with node foo.js prints a results array ['one', 'two'] as the docs indicate it will. 使用node foo.js运行它node foo.js打印一个结果数组['one', 'two']因为文档表明它会。 The thing I don't understand is how exactly this works: when you pass callback as a parameter to each function and then callback is called as callback(null, res) , what exactly is being called her? 我不明白的是它是如何工作的:当你将callback作为参数传递给每个函数然后callback被称为callback(null, res) ,究竟是什么叫做她? I've not actually defined any function callback, nor have I passed any sort of operating callback function as a parameter, yet everything magically works fine. 我实际上没有定义任何函数回调,也没有将任何类型的操作回调函数作为参数传递,但一切都神奇地工作正常。 Am I totally missing the point here? 我完全忽略了这一点吗? Or is this actually the under-the-hood magic of async ? 或者这实际上是async的引擎盖下的魔力?

You are not the one passing callback to the task functions, the async module is . 不是那个传递callback任务函数的人, async模块 It's a special function that the module passes to your task functions that when called, checks if any more tasks are left. 这是一个特殊的函数,模块传递给您的任务函数,在调用时,检查是否还剩下任务。

Here is something similar to what is being done inside async : 这与async内容类似:

function myParallel(tasks, finalcb) {
  var tasksLeft = tasks.length,
      results = [],
      ignore = false;

  function callback(err, result) {
    if (ignore) return;
    if (err) {
      ignore = true;
      finalcb && finalcb(err);
    } else if (--tasksLeft === 0) {
      ignore = true;
      finalcb && finalcb(null, results);
    } else
      results.push(result);
  }

  tasks.forEach(function(taskfn) {
    taskfn(callback);
  });
}

myParallel([
  function(callback) {
    setTimeout(function() {
      callback(null, 'one');
    }, 800);
  },
  function(callback) {
    setTimeout(function() {
      callback(null, 'two');
    }, 100);
  }
], function(err, results){
  console.log(results)
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM