Promse基本配置
class Promise {
constructor(exector){
this.initValue()
this.bindThis()
try{
exector(this.resolve,this.reject)
}catch(e){
this.reject(e)
}
}
initValue(){
this.value=null
this.reason=null
this.state = 'pedding'
this.onResolveCallback=[]
this.onRejectCalllback=[]
}
bindThis(){
this.resolve = this.resolve.bind(this)
this.reject = this.reject.bind(this)
}
resolve(value){
if(this.state==='pedding'){
this.state= 'fulfilled'
this.value = value
if(this.onResolveCallback.length>0){
this.onResolveCallback.forEach(fn=>fn(this.value))
}
}
}
reject(reason){
if(this.state==='pedding'){
this.state = 'reject'
this.reason = reason
if(this.onRejectCalllback.length>0){
this.onRejectCalllback.forEach(fn=>fn(this.reason))
}
}
}
then(onfulfilled,onRejected){
if(typeof onfulfilled!='function'){
onfulfilled=function(value){
return value
}
}
if(typeof onRejected!='function'){
onfulfilled=function(reason){
throw reason
}
}
let promise2 = new Promise((resolve,reject)=>{
if(this.state==='pedding'){
this.onResolveCallback.push(function(value){
setTimeout(() => {
let x = onfulfilled(value)
Promise.resolvePromise(promise2,x,resolve,reject)
});
})
this.onRejectCalllback.push(function(reason){
setTimeout(() => {
try{
let x = onRejected(reason)
Promise.resolvePromise(promise2,x,resolve,reject)
}catch(e){
reject(e)
}
});
})
}
if(this.state==='fulfilled'){
setTimeout(() => {
try{
let x = onfulfilled(this.value)
Promise.resolvePromise(promise2,x,resolve,reject)
}catch(e){
reject(e)
}
});
}
if(this.state==='reject'){
setTimeout(() => {
try{
let x = onRejected(this.value)
Promise.resolvePromise(promise2,x,resolve,reject)
}catch(e){
reject(e)
}
});
}
})
return promise2
}
}
Promise.resolvePromise=function(promise2,x,resolve,reject){
if(x===promise2){
throw 'xxxxxx'
}
if(x instanceof Promise){
x.then(value=>{
Promise.resolvePromise(promise2,value,resolve,reject)
},reason=>{
reject(reason)
})
}else if(x!=null&&(typeof x==='function'||typeof x==='object')){
try{
let then = x.then
if(typeof x.then){
then.call(value=>{
Promise.resolvePromise(promise2,value,resolve,reject)
},reason=>{
reject(reason)
})
}
}catch(e){
reject(e)
}
}else{
resolve(x)
}
}
Promise.resolve
Promise.resolve=function(val){
return new Promise((resolve,reject)=>{
resolve(val)
})
}
Promise.reject
Promise.reject = function(val){
return new Promise((resolve,reject)=>{
reject(val)
})
}
Promise.race
Promise.race=function(arr){
return new Promise((resolve,reject)=>{
for(let i=0;i<arr.length;i++){
arr[i].then(resolve,reject)
}
})
}
Promise.all
Promise.all = function(promises){
let arr = []
let i=0
function getData(index,data){
arr[index] = data
i++
if(i===arr.length){
resolve(arr)
}
return new Promise((resolve,reject)=>{
for(let i=0;i<promises.lenght;i++){
promises[i].then(data=>{
getData(i,data)
},reject)
}
})
}
}