node js同步foreach简单的例子?

时间:2017-09-20 09:48:14

标签: node.js

我想处理nodejs异步问题。 请帮助我一个甜蜜的例子 - 如果你能够通过回调或回调相关的事情来做它会对我更好。

由于

1 个答案:

答案 0 :(得分:0)

示例示例

Foreach循环

var fs = require('fs')
var paths = ['/home' , '/root', '/var']
paths.forEach(function( path ) {
  fs.lstat( path, function(err, stat) {
    console.log( path, stat );
  });
});

For loop

for (var i = 0, c = paths.length; i < c; i++)
{
  // creating an Immiedately Invoked Function Expression
  (function( path ) {
    fs.lstat(path, function (error, stat) {
      console.log(path, stat);
    });
  })( paths[i] );
  // passing paths[i] in as "path" in the closure
}

递归

    function iteratePath(paths, i, max){
      if(i<max) {
       return;
      }else{
          fs.lstat( path, function(err, stat) {
            console.log( path, stat );
            //Recursive call back
            iteratePath(paths, i, max)
          });
        }
    }

var paths = ['/home' , '/root', '/var']
iteratePath(paths,0, size)

您可以使用async Using async/await with a forEach loop