async.auto和async.waterfall对比

概念解疑

  • 和使用的waterfall区别是什么呢?
  1. task的执行方式:auto每一个task都是并行执行的,甚至连result的function都并行执行,但是可以使用依赖函数的方式进行串行执行。但是很明显,waterfalll是通过callback串行
async.auto({
  step_1:(done)=>{
      console.log("step 1");
      done(null,“data 1”)
  },
  step_2:(done)=>{
      setTimeout(()=>{console.log("step 2");},5000)
  }
},(err,result)=>{
    console.log("result:",result);
})
//这里step 1先打印,然后再打印result,最后打印step2
  1. 参数的传递方式:waterfall数据只能从上一层传到下一层,不能隔层传递。auto在没有依赖的task的情况下,是不能访问到数据的,但是添加了依赖函数之后,可以在task的result参数中获取当前拥有的所有数据。
async.auto({
  step_1:(done)=>{
      console.log("step 1");
      done(null,“data 1”)
  },
  step_2:["step_1",(result,done)=>{
      setTimeout(()=>{console.log("step 2");},5000) 
      done(null,"aaa")
      //result:{"step_1":"data 1"}
  }]
},(err,result)=>{
    console.log("result:",result);
   // result:{"step_1":"data 1","steop_2:"aaa"}
})

//对于auto而言,task本身如果是function(类似于step1)就没有办法获取到数据,如果是数组(类似于step2)就可以获取到对象,并且是当前能够得到的所有数据对象。
  1. callback回调函数的作用:auto主要是用来存储数据的和错误判断,依赖task的时候采用来做执行控制。waterfall完全用来做执行控制和错误判断
async.auto({
  step_1:(done)=>{
      console.log("step 1");
      done(null,“data 1”) //回调函数:首先可以告诉step_2开始执行,然后传递参数“data 1”
  },
  step_2:["step_1",(result,done)=>{
      setTimeout(()=>{console.log("step 2");},5000) 
      done(null,"aaa") //只用来传递参数“aaa”
      //result:{"step_1":"data 1"}
  }]
},(err,result)=>{
    console.log("result:",result);
   // result:{"step_1":"data 1","steop_2:"aaa"}
})

  1. 最后result函数中的result类型不同,auto是对象,waterfall是数组

example

async.auto({
    get_data: function(callback) {
    //当task是function只能有一个参数就是回调函数
        console.log('in get_data');
    
        callback(null, 'data', 'converted to array'); //第一个参数:true就会直接结束async,false向下传递。剩下参数,会被当做result中“get_data”的value,如果一个值就是string类型,多个值就是array
    },
    make_folder: function(callback) {
     //这个函数会和上个函数是同步执行(因为当前没有耗时操作,因此执行会从上到下)
        callback(null, 'folder');
    },
    write_file: ['get_data', 'make_folder', function(results, callback) {
    //当函数的task是数组,那么function必须在前两个task执行完毕(就是第二个task调用callback的时候执行)再执行,也只有这种时候,这个function才有result这个参数
        console.log('in write_file', JSON.stringify(results));
        // once there is some data and the directory exists,
        // write the data to a file in the directory
        callback(null, 'filename');
    }],
    email_link: ['write_file', function(results, callback) {
        console.log('in email_link', JSON.stringify(results));
        // once the file is written let's email a link to it...
        // results.write_file contains the filename returned by write_file.
        callback(null, {'file':results.write_file, 'email':'user@example.com'});
    }]
}, function(err, results) {
//跟所有task同步执行,之前有耗时操作,必然先执行这个函数,但是之前如果有函数回调函数参数为false,那么会直接执行此函数 
    console.log('err = ', err);
    console.log('results = ', results);
});
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容