gpt4 book ai didi

javascript - 在 node.js 中运行串行操作

转载 作者:行者123 更新时间:2023-11-30 07:29:08 31 4
gpt4 key购买 nike

我有一个异步函数可以并行执行一些 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
})

我想在执行这些 shell 命令后 做一些事情,但我不知道如何使用异步库来做这件事。这些 shell 命令是并行执行的,因此无法注册在所有这些命令执行完后执行的处理程序。

有什么想法吗?

最佳答案

使用 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
})
});

关于javascript - 在 node.js 中运行串行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4357391/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com