<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ES11的Promise.allSettled方法</title>
</head>
<body>
<script type="text/javascript">
// 声明 2 个Promise
const p1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("商品数据 - 1");
}, 1000)
});
const p2 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("商品数据 - 2");
}, 1000)
});
// 调用 allSettled 方法
const res = Promise.allSettled([p1, p2]);
console.log(res); // [[PromiseState]]: "fulfilled" [[PromiseResult]]: Array(2) // Array(2)包含的是两个 Promise 实例 的 resolve 结果
</script>
</body>
</html>
如果我们在执行 Promise.allSettled(p1, p2); 就会报错
Uncaught (in promise) TypeError: object is not iterable (cannot read property Symbol(Symbol.iterator));
这是因为, Promise.allSettled() 的入参要求为 数组, Promise.allSettled([p1, p2]); 就可以了
此外,另一个方法 Promise.all(); 入参要求也是 数组,Promise.all([p1, p2]); 但是两个函数的返回结果不同