当前位置:网站首页>Implementation of mypromise

Implementation of mypromise

2022-04-23 20:19:00 wytraining

1. Achieve one MyPromise

function resolvePromise(promise2,x,resolve,reject){
    // Judge x Is it right? promise
    // The specification States : We allow others to scribble , This code can realize our promise And other people's promise  Interact 
    if(promise2 === x){// You can't wait for yourself to finish 
        return reject(new TypeError(' Circular reference '));
    }
    // x Yes, except for null Objects or functions other than 
    if(x !=null && (typeof x === 'object' || typeof x === 'function')){
        let called;// Failure to prevent base note from successful call 
        try{// Prevent taking then Is there an exception   object.defineProperty
            let then = x.then;// take x Of then Method  {then:{}}
            if(typeof then === 'function'){// If then If it's a function, you think it's a function promise
                //call The first parameter is this, Followed by successful callbacks and failed callbacks 
                then.call(x,y => {// If Y yes promise Just continue recursion promise
                    if(called) return;
                    called = true;
                    resolvePromise(promise2,y,resolve,reject)
                },r => { // As long as you fail, you fail 
                    if(called) return;
                    called = true;
                    reject(r);
                });
            }else{//then It's a common object , Just succeed directly 
                resolve(x);
            }
        }catch (e){
            if(called) return;
            called = true;
            reject(e)
        }
    }else{//x = 123 x Is a normal value   As the next then Successful parameters 
        resolve(x)
    }

}

class MyPromise {
    constructor (executor){
        // The default state is waiting 
        this.status = 'pending';
        this.value = undefined;
        this.reason = undefined;
        // Save successful callbacks 
        this.onResolvedCallbacks = [];
        // Save failed callbacks 
        this.onRejectedCallbacks = [];
        let resolve = (data) => {//this It's an example 
            if(this.status === 'pending'){
                this.value = data;
                this.status = "resolved";
                this.onResolvedCallbacks.forEach(fn => fn());
            }

        }
        let reject = (reason) => {
            if(this.status === 'pending'){
                this.reason = reason;
                this.status = 'rejected';
                this.onRejectedCallbacks.forEach(fn => fn());
            }
        }
        try{// Exceptions may occur during execution 
            executor(resolve,reject);
        }catch (e){
            reject(e);//promise failed 
        }

    }
    then(onFuiFilled,onRejected){
        // Prevent penetration 
        onFuiFilled = typeof onFuiFilled === 'function' ? onFuiFilled : y => y;
        onRejected = typeof onRejected === 'function' ? onRejected :err => {throw err;}
        let promise2;// For the next time then Methodical promise
       if(this.status === 'resolved'){
           promise2 = new MyPromise((resolve,reject) => {
               setTimeout(() => {
                  try{
                        // The logic of success   The logic of failure 
                        let x = onFuiFilled(this.value);
                        // see x Is it right? promise  If it is promise Take his results   As promise2 The result of success 
                        // If you return a normal value , As promise2 Successful results 
                        //resolvePromise Can be parsed x and promise2 The relationship between 
                        // stay resolvePromise Pass in four parameters , The first is the return promise, The second is the result returned , The third and fourth are resolve() and reject() Methods .
                        resolvePromise(promise2,x,resolve,reject)
                  }catch(e){
                        reject(e);
                  }
               },0)
           });
       }
       if(this.status === 'rejected'){
            promise2 = new MyPromise((resolve,reject) => {
                setTimeout(() => {
                    try{
                        let x = onRejected(this.reason);
                        // stay resolvePromise Pass in four parameters , The first is the return promise, The second is the result returned , The third and fourth are resolve() and reject() Methods .
                        resolvePromise(promise2,x,resolve,reject)
                    }catch(e){
                        reject(e);
                    }
                },0)

            });
       }
       // There is neither completion nor failure at present 
       if(this.status === 'pending'){
           promise2 = new MyPromise((resolve,reject) => {
               // Store the successful functions one by one in the successful callback function array 
                this.onResolvedCallbacks.push( () =>{
                    setTimeout(() => {
                        try{
                            let x = onFuiFilled(this.value);
                            resolvePromise(promise2,x,resolve,reject);
                        }catch(e){
                            reject(e);
                        }
                    },0)
                });
                // Store the failed functions one by one in the failed callback function array 
                this.onRejectedCallbacks.push( ()=>{
                    setTimeout(() => {
                        try{
                            let x = onRejected(this.reason);
                            resolvePromise(promise2,x,resolve,reject)
                        }catch(e){
                            reject(e)
                        }
                    },0)
                })
           })
       }
       return promise2;// call then Then return to a new promise
    }
    catch (onRejected) {
        // catch  The way is then There is no shorthand for success 
        return this.then(null, onRejected);
    }
}
MyPromise.all = function (promises) {
    //promises It's a promise Array of 
    return new MyPromise(function (resolve, reject) {
        let arr = []; //arr Is the result of the final return value 
        let i = 0; //  Indicates how many times you have succeeded 
        function processData(index, data) {
            arr[index] = data;
            if (++i === promises.length) {
                resolve(arr);
            }
        }
        for (let i = 0; i < promises.length; i++) {
            promises[i].then(function (data) {
                processData(i, data)
            }, reject)
        }
    })
}

//  As long as there is one promise succeed   Even if it succeeds . If the first one fails, it fails 
MyPromise.race = function (promises) {
    return new MyPromise((resolve, reject) => {
        for (var i = 0; i < promises.length; i++) {
            promises[i].then(resolve,reject)
        }
    })
}
//  Generate a successful promise
MyPromise.resolve = function(value){
    return new MyPromise((resolve,reject) => resolve(value));
}
//  Generate a failed promise
MyPromise.reject = function(reason){
    return new MyPromise((resolve,reject) => reject(reason));
}
MyPromise.defer = MyPromise.deferred = function () {
    let dfd = {};
    dfd.MyPromise = new MyPromise( (resolve, reject) =>  {
        dfd.resolve = resolve;
        dfd.reject = reject;
    });
    return dfd
}

2. call

let p =  new MyPromise((resolve, reject)=>{
    setTimeout(()=>{
        console.log('ok')
        resolve(' success ')
    }, 2000)
})

p.then(data=>{
    console.log(data)
})

Promise Can't ?? Look here !!! The most accessible thing in history Promise!!!

版权声明
本文为[wytraining]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204210552098072.html

随机推荐