<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<script>
let p1 = new Promise((resolve, reject) => {
resolve('成功了')
})
let p2 = new Promise((resolve, reject) => {
resolve('success')
})
let p3 = Promise.reject('失败')
let p4 = Promise.reject('失败4')
// 这种事失败成功都会返回
Promise.allSettled([p1, p3, p2,p4,p2])
.then((results) => {
/***
* results是一个数组,内容如下
* [
* {status:'fulfilled',value:'成功了'},
* {status:'rejected',value:'失败'},
* {status:'fulfilled',value:'成功了'},
* {status:'rejected',value:'失败4'},
* {status:'fulfilled',value:'成功了'},
*
* ]
*/
console.log('不管有没有成功失败,我这都会执行:', results);
results.forEach((result) => {
if (result.status === 'fulfilled') {
console.log('成功:', result.value);
} else {
console.log('失败:', result.reason);
}
});
});
// 这种是 只要有失败就会退出发送请求的行为
Promise.all([p1, p3, p2,p4,p2]).then((result) => {
console.log(result)
}).catch((error) => {
console.log(error) // 失败了,打出 '失败'
})
</script>
</body>
</html>
运行结果: