前言
我们知道promise是es6中异步解决方案,极大的改善了回调地狱的问题,promise中也有很多api是我们日常开发中高频使用的,这里着重介绍Promise.all与Promise.race
Promise.all
我们使用Promise.all场景大多数是在需要一次性发送多次没有关联的请求,而它刚好能并行发送http请求,避免了网络拥塞情况,下面是实现原理
Promise.prototype.myAll = function (array) {
if(!Array.isArray(array)) { return new Error('argument is no Array')}
let result = new Array(array.length),
count = 0
return new Promise((resolve, reject) => {
array.forEach(item => {
Promise.resolve(item)
.then(data => {
result.push(data)
count ++
if( count === array.length) {
resolve(result)
}
}).catch( error => {
reject(error)
// 捕获异常
//当一次错误时候即停止并返回第一个错误的捕获
})
})
})
}
Promise.race
我们使用Promise.race场景大多数是在我们向多个服务器发送请求,将最快返回的服务器值渲染至页面,因为race返回的是最快的那个,下面是实现原理
Promise.prototype.myRace = function (array) {
if(!Array.isArray(array)) { return new Error('argument is no Array')}
return new Promise((resolve, reject) => {
array.forEach(item => {
Promise.resolve(item).then(data => {
resolve(data)
}).catch(err => {
reject(err)
})
})
})
}