如何循环承诺?

时间:2017-09-19 01:27:36

标签: javascript asynchronous promise es6-promise

    var arr = ["node.js", "Java", "C#"];
var newArr = [];

let promise = new Promise((resolve, reject) => {

        for(let i = 0; i < arr.length; i++) {
            setTimeout(() => {
                newArr.push(arr[i])
                resolve(newArr);
            }, 1000);
        }

});

promise
        .then(result => {
             alert(result);
         }
);

现在它在第一次循环后警告数据。如何在通过整个循环后使用promises显示来自异步操作的数据?

所需行为:以异步模式向newArr添加数据,并在循环结束后显示。

1 个答案:

答案 0 :(得分:2)

您需要与promise all

签订多个承诺

&#13;
&#13;
const myPromises = [];
for (let i=0; i<5; i++) {
  myPromises.push(new Promise((resolve, reject) => {
      setTimeout(() => {
        console.log("done", i);
        resolve(i)
      } , i*500);
  })); 
}

Promise.all(myPromises).then(values => { 
  console.log("All: ", values)
});
&#13;
&#13;
&#13;