Promise对象all与race方法手写示例
作者:大眼睛图图
这篇文章主要为大家介绍了Promise对象all与race方法手写示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
前言
在理解了手写promsie.then的方法后,再来看它的其他方法,感觉真的简单了不少。
Promise.all
介绍
Promise.all()方法用于将多个 Promise 实例,包装成一个新的 Promise 实例。
const p = Promise.all([p1, p2, p3]);
上面代码中,Promise.all()方法接受一个数组作为参数,p1、p2、p3都是 Promise 实例。另外,Promise.all()方法的参数可以不是数组,但必须具有 Iterator 接口,且返回的每个成员都是 Promise 实例。
p的状态由p1、p2、p3决定,分成两种情况。
(1)只有p1、p2、p3的状态都变成fulfilled,p的状态才会变成fulfilled,此时p1、p2、p3的返回值组成一个数组,传递给p的回调函数。
(2)只要p1、p2、p3之中有一个被rejected,p的状态就变成rejected,此时第一个被reject的实例的返回值,会传递给p的回调函数。
手写
- 返回一个
Promsie对象
const promiseAll = (array) => {
return new Promise((resolve, reject) => {
})
}
- 判断传入的是数组
const promiseAll = (array) => {
if (!Array.isArray(array)) {
throw new Error('要传入数组')
}
return new Promise((resolve, reject) => {
}
}
- 遍历数组,再判断数组中每个元素是否为
Promsie对象的实例,并对此分情况处理
const promiseAll = (array) => {
if (!Array.isArray(array)) {
throw new Error('要传入数组')
}
return new Promise((resolve, reject) => {
let result = [];
array.forEach((item, index) => {
if (item instanceof Promise) {
item.then(res => {
result[index] = res
},
err => { return reject(err) })
} else {
result[index] = item
}
})
})
}
- 设置一个计数器
count,当遍历完了所有数组里面的值,就把result数组打印出来
const promiseAll = (array) => {
if (!Array.isArray(array)) {
throw new Error('要传入数组')
}
return new Promise((resolve, reject) => {
let result = [];
let count = 0;
array.forEach((item, index) => {
if (item instanceof Promise) {
item.then(res => {
result[index] = res
count++;
if (count == array.length) {
return resolve(result)
}
},
err => { return reject(err) })
} else {
result[index] = item
count++;
if (count == array.length) {
return resolve(result)
}
}
})
})
}
Promise.race
介绍
Promise.race()方法同样是将多个 Promise 实例,包装成一个新的 Promise 实例。
const p = Promise.race([p1, p2, p3]);
上面代码中,只要p1、p2、p3之中有一个实例率先改变状态,p的状态就跟着改变。那个率先改变的 Promise 实例的返回值,就传递给p的回调函数。
手写
- 返回一个
Promise对象
let promiseRace = (array) => {
return new Promise((resolve, reject) => {
})
}
- 判断传入的参数是否为数组
let promiseRace = (array) => {
if (!Array.isArray(array)) {
throw new Error('要返回数组')
}
return new Promise((resolve, reject) => {
})
}
- 遍历数组,再判断数组中每个元素是否为
Promsie对象的实例,再对此分情况处理
let promiseRace = (array) => {
if (!Array.isArray(array)) {
throw new Error('要返回数组')
}
return new Promise((resolve, reject) => {
array.forEach((item) => {
if (item instanceof Promise) {
item.then(res => {
return resolve(res)
},
err => reject(err))
} else {
return resolve(item)
}
})
})
}
参考文档
以上就是Promise对象all与race方法手写示例的详细内容,更多关于Promise对象all race方法的资料请关注脚本之家其它相关文章!
