function mypromise(fn) {
this.cache = null;
this.resolve = (value) => {
this.data = value;
this.cache(value);
};
fn&&fn(this.resolve);
}
mypromise.prototype.then = function (func_onResolved) {
this.cache = func_onResolved;
};
mypromise.prototype.all = function (arr = []) {
const resCache=[]
for (let index = 0; index < arr.length; index++) {
arr[index]().then((res)=>{
resCache.push({res,index})
if(resCache.length===arr.length){
this.resolve(resCache.sort(function(a,b){
if(a.index>b.index){
return 1
}
return -1
}).map(_=>_.res))
}
})
}
return this
}
const task1=function(){
return new mypromise(resolve=>{
setTimeout(()=>{
resolve(5)
},2000)
})
}
const task2=function(){
return new mypromise(resolve=>{
setTimeout(()=>{
resolve(2)
},1000)
})
}
new mypromise().all([task1,task2]).then(res=>{
console.log(res,'res');
})