美文网首页js
promise相关

promise相关

作者: 马甲要掉了 | 来源:发表于2020-08-25 17:00 被阅读0次

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);
}

相关文章

  • Promise相关

    在 javascript 中, 所有代码都是单线程执行的。 由于这个缺陷,导致 javascript 的所有网络操...

  • promise相关

    promise promise.race promise.finally promise.catch

  • Promise相关

    https://segmentfault.com/a/1190000039275224[https://segme...

  • promise相关

    异步编程 *fs文件操作*数据库操作*ajax*定时器在promise之前的解决方式: 旧的解决方法:必须在启动异...

  • Promise相关题目

    实现一个person对象,有eat和dinner两种方法请用实例【依次类推】new Person('Tom').s...

  • Promise相关知识

    一、Promise基础 1.为什么需要Promise? js是一门单线程语言,所以早期我们在解决异步的场景时,通常...

  • Promise相关概念

    Promise 检测图片 检测图片是否加载成功,成功就正常显示,失败就展示默认图片 休眠的实现方法 基本用法 有一...

  • 深入了解下Promise

    Promise 意义 Promise 的诞生与 Javascript 中异步编程息息相关,js 中异步编程主要指 ...

  • 「超全」手写Promise的相关方法

    原文发布在:手写Promise的相关方法。 摘要 Promise 作为 JS 社区的异步解决方案,为开发者提供了....

  • UIWebView的touch的事件

    滚动的事件绑定touch相关事件的时候使用Promise异步方法回调丢失 由于ios没有自带的Promise,在P...

网友评论

    本文标题:promise相关

    本文链接:https://www.haomeiwen.com/subject/mwyzjktx.html