我遇到了一个棘手的情况,需要收集属于某些类型(给定数组中的类型)的键,然后过滤收集的键并传递给删除函数。
收集过程调用 shell 代码并在循环内的回调中处理结果。我需要等到整个回调循环完成然后传递给删除函数。
我在 Node 代码中使用shelljs,基本上如下所示:
var del_arr = [];
for (var i in types) {
shell.exec(somecode with
var [i], {
silent: true
},
function(code, stdout, stderr) {
somecode-processing/filtering stdout and pushes the results to del_arr;
});
//loop through array types[] and need to wait for all shell codes' callbacks to finish;
}
//then pass del_arr to deletion function
我无法以 shelljs 回调的这种格式 b/s 构建异步函数。我也不知道在这种情况下如何使用 Promise。
你能告诉我如何实现这个非阻塞过程吗? 谢谢
最佳答案
将 child_process.exec
变成一个 promise :
function execWrapper(command, options) {
return new Promise((resolve, reject) => {
shell.exec(command, options, (error, out, err) => {
if (error) return reject(error);
resolve({out: out, err: err});
})
})
}
然后你可以迭代类型并将每个类型映射到一个 promise :
const promises = types.map(type => execWrapper(type, {slient: true}));
现在等待每个 promise 得到解决,或者等待一个 promise 被拒绝:
Promise.all(promises).then((del_arr) => {
// del_arr is now a array of objects with the stdout and stderr of each type.
//
})
关于JavaScript 在带有回调的循环中异步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51129156/