成品代码
Promise.myall = function(list){
let results = []
let count = 0
return new Promise((resolve,reject) => {
list.map( (promise,index) => {
promise.then((r) => {
results[index] = r
count += 1
if(count >= list.length){
resolve(results)
}
},(reason) => {
reject(reason)
})
})
})
}
流程:
- 不能再 Promise 的原型上写。
Promise.myall = function(){
}
- 根据 Promise.all ,我们手写的 myall ,参数得是一个装着 Promise 的数组;因为myall成功了也要调用 promise,所以需要return 新的 promise。
Promise.myall = function(list){
return new Promise((resolve,reject) => {
list.map( (promise,index) => {
promise.then((r) => {
},() => {
})
})
})
}
- 每个 Promise 成功的值需要加到一个数组里存储。
Promise.myall = function(list){
let results = []
let count = 0
return new Promise((resolve,reject) => {
list.map( (promise,index) => {
promise.then((r) => {
results[index] = r
count += 1
if(count >= list.length){
resolve(results)
}
},() => {
})
})
})
}
- 只要有一个失败就直接失败。
Promise.myall = function(list){
let results = []
let count = 0
return new Promise((resolve,reject) => {
list.map( (promise,index) => {
promise.then((r) => {
results[index] = r
count += 1
if(count >= list.length){
resolve(results)
}
},(reason) => {
reject(re)
})
})
})
}