代码之家  ›  专栏  ›  技术社区  ›  aRvi

异步之间的差异。每个vs异步。每个?

  •  2
  • aRvi  · 技术社区  · 7 年前

    ? 纠正我,我错了。

    2 回复  |  直到 7 年前
        1
  •  3
  •   Prabodh M    7 年前

    异步每个

    .each(coll, iteratee, callback)
    

    它更像是数组中的每一种方法。这里,在每个Iterable(coll)元素上,函数 iteratee 将被执行。这将平行进行。因此,以现场为例

    async.each(openFiles, saveFile, function(err){
      // if any of the saves produced an error, err would equal that error
    });
    

    这里假设 openFiles 是文件路径的数组。所以 saveFile 打开文件 。如果任何元素导致saveFile中出现错误,该函数将调用带有错误的邮件回调,并停止进程。

    异步间隔

    .every(coll, iteratee, callback)
    

    这似乎是同样的方法。因为它还执行 方法结束 coll 元素。但关键是,它也会返回 true false 。它更像一个过滤器,但唯一的区别是它返回 如果 科尔 iteratee方法失败。不要将此处与错误混淆。如果在执行过程中发生一些不确定的行为,则会导致错误。所以 callback callback(err, result) 。结果是真是假取决于 科尔 通过迭代测试。

    对于eg,检查数组是否有偶数;

    async.every([4,2,8,16,19,20,44], function(number, callback) {
          if(number%2 == 0){
             callback(null, true);
          }else{
            callback(null, false);
          }
    }, function(err, result) {
        // if result is true when all numbers are even else false
    });
    

        2
  •  3
  •   Ratan Uday Kumar coroutineDispatcher    7 年前

    每个(arr、迭代器、[回调])

    将函数迭代器并行应用于arr中的每个项。迭代器由列表中的一个项调用,并在完成时回调。如果迭代器将错误传递给其回调,则会立即使用错误调用主回调(对于每个函数)。

    注意,由于此函数将迭代器并行应用于每个项,因此不能保证迭代器函数将按顺序完成。

    arr-要迭代的数组。 回调(err)-可选回调,在所有迭代器函数完成或发生错误时调用。 示例

    // assuming openFiles is an array of file names and saveFile is a function
    // to save the modified contents of that file:
    
    async.each(openFiles, saveFile, function(err){
        // if any of the saves produced an error, err would equal that error
    });
    // assuming openFiles is an array of file names
    
    async.each(openFiles, function(file, callback) {
    
      // Perform operation on file here.
      console.log('Processing file ' + file);
    
      if( file.length > 32 ) {
        console.log('This file name is too long');
        callback('File name too long');
      } else {
        // Do work to process file here
        console.log('File processed');
        callback();
      }
    }, function(err){
        // if any of the file processing produced an error, err would equal that error
        if( err ) {
          // One of the iterations produced an error.
          // All processing will now stop.
          console.log('A file failed to process');
        } else {
          console.log('All files have been processed successfully');
        }
    });
    

    如果arr中的每个元素都满足异步测试,则返回true。每个迭代器调用的回调只接受单个参数true或false;它首先不接受错误参数!这与节点库处理fs.exists等真值测试的方式一致。

    arr-要迭代的数组。 迭代器(项,回调)-并行应用于数组中每个项的真值测试。迭代器被传递一个回调(truthValue),完成后必须用布尔参数调用该回调。 注意:回调不会将错误作为其第一个参数。

    async.every(['file1','file2','file3'], fs.exists, function(result){
        // if result is true then every file exists
    });