在node.js中运行串行操作

ajs*_*sie 1 javascript callback node.js

我有一个异步函数,可以并行执行一些shell命令

require("fs").readdir("./", function (error, folders) { // asynched
    require("underscore")._(folders).each(function (folder, folderKey, folderList) { // asynched
    r("child_process").exec("ls ./" + folder, function(error, stdout, stderr) {
           console.log("Cant put it here") // Will be run after the first execution is completed
        })
        console.log("Cant put it here either") // Will be run immediately before any execution is completed
    })
    console.log("Cant put it here either") // Will be run immediately before any execution is completed
})
Run Code Online (Sandbox Code Playgroud)

我希望在执行这些shell命令执行某些操作,但我无法弄清楚如何使用异步库执行此操作.这些shell命令是并行执行的,因此无法注册在执行所有这些命令执行的处理程序.

有任何想法吗?

Cao*_*lan 5

使用async.js库:https://github.com/caolan/async

var fs = require('fs');
var async = require('async');
var exec = require('child_process').exec;

fs.readdir("./", function (error, folders) {
    async.forEach(folders, function (folder, callback) {
        exec("ls ./" + folder, function (error, stdout, stderr) {
            callback();
        });
    },
    function (error) {
        // this is called after all shell commands are complete
    })
});
Run Code Online (Sandbox Code Playgroud)