使用 Promise.all() 并行处理多个 Promise。Promise.all() 接收一个实现了 Promise 接口的迭代器(通常是一个数组或者类数组对象),并返回一个新的 Promise,该 Promise 等待迭代器中的所有 Promise 都完成后才会被 resolved。在所有 Promise 都被 resolved 后,返回的Promise的 resolved value 会是一个数组,包含了传递给 Promise.all() 的每个 Promise 的 resolved value。如果其中任何一个 Promise 被 rejected, Promise.all() 返回的 Promise 将立即被 rejected 并返回rejected的 Promise 的原因。
以下是一个使用 Promise.all() 实现并行获取两个 API 数据的例子:
const promise1 = fetch('api1');
const promise2 = fetch('api2');
Promise.all([promise1, promise2])
.then(([response1, response2]) => {
// 处理 response1 和 response2
})
.catch((error) => {
console.error(error);
});
在上面的代码中,使用 fetch() 函数获取两个 API 的数据,将它们分别存储在 promise1 和 promise2 变量中,然后传递给 Promise.all(),在回调函数中可以访问每个 Promise 的响应对象。
insert(){
let insertA = this.$http({
method: "post",
url: "asdfghjkl/insert",
timeout: 0,
data: this.rowDataA,
});
let insertB = this.$http({
method: "post",
url: "asdfghjkl/insert",
timeout: 0,
data: this.rowDataB,
});
Promise.all([insertA, insertB]).then((resList) => {
for (let i = 0; i < resList.length; i++) {
const res = resList[i];
if (res.data.code === 200) {
this.$message({
message: "新增成功.",
duration: 4000,
showClose: true,
type: "success",
});
} else {
this.$message({
message: res.data.msg,
duration: 3000,
showClose: true,
type: "error",
});
return false;
}
}
})
}