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添加数据,并在循环结束后显示。
答案 0 :(得分:2)
您需要与promise all
签订多个承诺
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;