Javascript 等待里面有承诺的forEach完成

Javascript 等待里面有承诺的forEach完成,javascript,Javascript,我在等待我的forEach循环完成时遇到了一个问题,它里面有一个承诺。我找不到任何真正的解决方案,这会让脚本等到最后,然后再继续执行。我无法使someFunction同步 makeTree: function (arr) { arr.forEach(function (resource) { someModule.someFunction(resource).then(function () { //a Promise //do something

我在等待我的forEach循环完成时遇到了一个问题,它里面有一个承诺。我找不到任何真正的解决方案,这会让脚本等到最后,然后再继续执行。我无法使someFunction同步

makeTree: function (arr) {
    arr.forEach(function (resource) {
        someModule.someFunction(resource).then(function () { //a Promise
            //do something with the resource that has been modified with someFunction
        });
    });
    // do something after the loop finishes
}
使用
map()
创建承诺数组,然后使用

使用
map()
创建承诺数组,然后使用

试试这个

makeTree: function (arr) {
   var promises = [];
   arr.forEach(function(resource) {
      promises.push(someModule.someFunction(resource));
   });
   Promise.all(promises).then(function(responses) {
      // responses will come as array of them
      // do something after everything finishes
   }).catch(function(reason) {
      // catch all the errors
      console.log(reason);
   });
}
你可以参考这篇文章来了解更多关于承诺的内容。所有的都有简单的例子。

试试这个

makeTree: function (arr) {
   var promises = [];
   arr.forEach(function(resource) {
      promises.push(someModule.someFunction(resource));
   });
   Promise.all(promises).then(function(responses) {
      // responses will come as array of them
      // do something after everything finishes
   }).catch(function(reason) {
      // catch all the errors
      console.log(reason);
   });
}

你可以参考这篇文章了解更多关于
Promise的信息。所有的
都有简单的例子。

你在使用angularjs吗?你在使用angularjs吗?非常感谢你的回答,我也有同样的疑问,我不想处理包或复杂的事情。这是对这些案例的最佳回应,非常简单和精彩。再次感谢。RegardSimple and clear to read+维护:感谢您提供此解决方案!如果我的功能没有任何回报,就不为我工作。非常感谢你的回答,我也有同样的疑问,我不想处理软件包或其他复杂的事情。这是对这些案例的最佳回应,非常简单和精彩。再次感谢。RegardSimple and clear to read+维护:感谢您提供此解决方案!如果我的函数没有返回任何内容,则不为我工作