promise
let FULFILLED= 'fulfilled';
let REJECT = 'reject';
let PENDING = 'pending';
class Promise1{
constructor(excutor){
let that = this;
that.status = PENDING;
that.value = null;
that.reason = null;
that.onFulfilledCallbacks = [];
that.onRejectedCallbacks = [];
let resolve = function(value){
if(that.status == PENDING){
that.status = FULFILLED;
that.value = value;
that.onFulfilledCallbacks.map((cb)=>cb())
}
}
let reject = function(reason){
if(that.status == PENDING){
that.status = REJECT;
that.reason = reason;
that.onRejectedCallbacks.map((cb)=>cb());
}
}
try{
excutor(resolve,reject);
}catch(e){
reject(e);
}
}
then(onFulfilled,onRejected){
let that = this;
if(that.status==FULFILLED){
onFulfilled(that.value);
}
if(that.status==REJECT){
onRejected(that.reason);
}
if(that.status==PENDING){
that.onFulfilledCallbacks.push(()=>{
onFulfilled(that.value);
})
that.onRejectedCallbacks.push(()=>{
onRejected(that.reason);
})
}
}
}
let promise = new Promise1((resolve,reject)=>{
resolve('1');
setTimeout(()=>{
console.log('time')
},0)
})
promise.then((value)=>{
console.log('2',value);
},()=>{
console.log('3');
})
promise.then(()=>{
console.log('4')
setTimeout(()=>{
console.log('lalal')
},1000)
}) // 1 2 4 time lalal
Promise.all1 = function(values){
return new Promise((resolve,reject)=>{
let arr = [];
for(let i=0;i<values.length;i++){
let cur = values[i];
if(isPromise(cur)){
cur.then((data)=>{
processData(i,data);
},reject)
}else{
processData(i,cur);
}
}
let processData = (key,value)=>{
arr[key] = value;
if(++key == values.length){
resolve(arr);
}
}
})
}
let p1 = new Promise((resolve, reject) => {
resolve('成功了')
})
let p2 = new Promise((resolve, reject) => {
resolve('success')
})
let p3 = Promise.reject('失败')
Promise.all1([p1, p2]).then((result) => {
console.log(result) //['成功了', 'success']
}).catch((error) => {
console.log(error)
})
Promise.all1([p1,p3,p2]).then((result) => {
console.log(result)
}).catch((error) => {
console.log(error) // 失败了,打出 '失败'
})
promise.race
function isPromise(x){
if(typeof x === 'function' || (typeof x === 'object' && x!=null)){
return true;
}
return false;
}
Promise.race1 = function(values){
return new Promise((resolve,reject)=>{
for(let i=0;i<values.length;i++){
if(isPromise(values[i])){
values[i].then(resolve,reject);
}else{
resolve(values[i]);
}
}
})
}
Promise.race1([p1, p2]).then((result) => {
console.log(result) //成功了
}).catch((error) => {
console.log(error)
})
Promise.race1([p3,p2]).then((result) => {
console.log(result)
}).catch((error) => {
console.log(error) //失败
})
promise.finally
Promise.resolve = function(value){
return new Promise((this.resolve,reject)=>{
resolve(value);
})
}
Promise.prototype.finally = function(callback){
return this.then((data)=>{
return Promise.resolve(callback()).then(()=>data);
},err=>{
return Promise.resolve(callback().then(()=>{throw err}));
})
}
promise.catch
Promise.prototype.catch = function(callback){
return this.then(null,callback);
}