JavaScript 在带有回调的循环中异步

标签 javascript node.js asynchronous ecmascript-6 es6-promise

我遇到了一个棘手的情况,需要收集属于某些类型(给定数组中的类型)的键,然后过滤收集的键并传递给删除函数。

收集过程调用 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/

相关文章:

javascript - 如何停止在 node.js 中获取此 ReferenceError?

c# - 如何等待(在异步方法中)包含 C# 方法调用的 linq 请求

asynchronous - Rust 异步程序中的性能和内存问题

c# - .Net Core Async 关键部分(如果在同一实体上工作)

javascript - jQuery/深/委派

javascript - 如何获取colspan的值

javascript - 将元素插入标题

node.js - 为什么 ObjectID 没有在 Mongodb 中定义?

node.js - Sequelize .create 没有为我的模型生成内容

javascript - 使用 Promise 时出现重复的 Mongoose 日志条目