Promise.allSettled 解决了 Promise.all 的只要一个请求失败了就会抛出错误的问题,当我们一次发起多个请求时,所有结果都能返回,无论成功或失败。
// axios.all同时发起多个请求时的处理
const promise1 = Promise.resolve('hello')
const promise2 = new Promise((resolve, reject) => setTimeout(reject, 200, 'problem'))
Promise.allSettled([promise1, promise2])
.then((values) => {
console.log(values)
})

比较两者:Promise.allSettled()与Promise.all()方法
Promise.allSettled()
接收参数为promise数组,返回promise对象,状态永远为成功
始终能够得到每一个promise成功失败的结果
//声明两个promise对象
const p1 = new Promise((resolve, reject) =>{
setTimeout(()=>{
resolve('商品数据-1');
},1000)
})
const p2 = new Promise((resolve, reject) =>{
setTimeout(()=>{
// resolve('商品数据-2');
reject('失败的数据');
},1000)
})
//调用allSettled方法
const result = Promise.allSettled([p1,p2]);
console.log(result)

Promise.all()
返回的是promise对象,返回状态有一个失败且都失败,
失败的值为数组里面失败的值
//声明两个promise对象
const p3 = new Promise((resolve, reject) =>{
setTimeout(()=>{
resolve('商品数据-1');
},1000)
})
const p4 = new Promise((resolve, reject) =>{
setTimeout(()=>{
// resolve('商品数据-2');
reject('失败的数据');
},1000)
})
//调用all方法
const result1 = Promise.all([p3,p4]);
console.log(result1)//rejected

总结:
什么时候用 Promise.allSettled()?
什么时候用 Promise.all()?
-每一个异步任务都想得到结果就使用Promise.allSettled()
-异步任务要求每个都成功才能往下执行就使用Promise.all()
完善Promise的allSettled方法,解决浏览器的一些兼容性问题
Promise.allSettled = Promise.allSettled || function(arr) {
// let P = this
return new Promise((resolve, reject) => {
if(Object.prototype.toString.call(arr) !== '[object Array]') {
return reject(new TypeError(typeof arr + '' + arr + '' + 'is not iterable(cannot read property Symbol(Symbol.iterator))'))
}
var args = Array.prototype.slice.call(arr)
if(args.length === 0) return resolve([])
var arrCount = args.length
function resolvePromise(index, value){
if(typeof value === 'object') {
var then = value.then
if(typeof then === 'function') {
then.call(value, function(val){
args[index] = {status: 'fulfilled', value: val}
if(--arrCount === 0) {
resolve(args)
}
}, function(e) {
args[index] = {status: 'rejected', reason: e}
if(--arrCount === 0){
resolve(args)
}
})
}
}
}
for(let i = 0; i < args.length; i++) {
resolvePromise(i, args[i])
}
})
}
实际项目中使用:
// 创建产品
//封装的axios方法返回一个promise对象
addInstances (params){
return this.$httpRequestEntrance.httpRequestEntrance('POST',this.apiCenter.ECS.instance.instance_manage.CRUD,
params, (res) => res)
},
let postArr= []
for(let i = 0; i < this.number; i++){
postArr.push(this.addInstances(params))
}
}
Promise.allSettled(postArr).then(results => {
console.log(results )
})
网友评论