手写实现一个promise

function myPromise (callback) {

let self = this;

self.status = 'pending';

self.value = undefined;

self.reason = undefined;

self.fullFiledArr = [];

self.rejectedArr = [];

function resolve (value) {

if(self.status == 'pending') {

self.value = value;

self.status = 'fufilled';

self.fullFiledArr.forEach(function(f) {

f.call(this,self.value)

});

}

}

function reject (reason) {

if(self.status == 'pending') {

self.reason = reason;

self.status = 'rejected';

self.rejectedArr.forEach(function(f) {

f(self.reason)

});

}

}

try{

callback(resolve,reject);

} catch(e) {

reject(e);

}

}

myPromise.prototype.then = function (onFufilled,onRejected) {

let self = this;

let myPromise2;

switch(self.status) {

case 'pending':

myPromise2 = new myPromise(function(resolve,reject) {

self.fullFiledArr.push(function(){

try{

let res = onFufilled(self.value);

if(res instanceof myPromise) {

res.then(resolve,reject);

}

// resolvePromise(myPromise,res);

} catch(e) {

reject(e);

}

})

self.rejectedArr.push(function(){

try{

let res = onRejected(self.reason);

if(res instanceof myPromise) {

res.then(resolve,reject);

}

} catch(e) {

reject(e);

}

})

});

break;

case 'fufilled':

myPromise2 = new myPromise(function(resolve,reject) {

try{

let res = onFufilled(self.value);

if(res instanceof myPromise) {

res.then(resolve,reject);

}

} catch(e) {

reject(e);

}

});

break;

case 'rejected':

myPromise2 = new myPromise(function(resolve,reject) {

try{

let res = onRejected(self.reason);

if(res instanceof myPromise) {

res.then(resolve,reject);

}

} catch(e) {

reject(e);

}

})

}

return myPromise2;

}

 

function resolvePromise(promise,x,resolve,reject){

if(promise===x){

throw new TypeError("type error")

}

let isUsed;

if(x!==null&&(typeof x==="object"||typeof x==="function")){

try{

let then=x.then;

if(typeof then==="function"){

//是一个promise的情况

then.call(x,function(y){

if(isUsed)return;

isUsed=true;

resolvePromise(promise,y,resolve,reject);

},function(e){

if(isUsed)return;

isUsed=true;

reject(e);

})

}else{

//仅仅是一个函数或者是对象

resolve(x)

}

}catch(e){

if(isUsed)return;

isUsed=true;

reject(e);

}

}else{

//返回的基本类型,直接resolve

resolve(x)

}

}


 

const async1 = () => {

var p = new myPromise((resolve,reject)=> {

console.log('1');

setTimeout(()=>{

resolve('链式调用1');

},1000)

})

return p;

}

const async2 = () => {

var p = new myPromise((resolve,reject)=> {

console.log('2');

setTimeout(()=>{

resolve('链式调用2');

},1000)

})

return p;

}

 

async1().then((data) => {

console.log(data);

return async2();

}).then((data)=>{

console.log(data);

})

 

你可能感兴趣的:(javascript)