当前位置:网站首页>Promise [II. Promise source code] [detailed code comments / complete test cases]

Promise [II. Promise source code] [detailed code comments / complete test cases]

2022-06-27 03:25:00 Yiyao Bingo

Hand rolling Promise That is to finish promise The main function of

  • Declaration constructor
    • resolve And reject
    • throw Throw an exception to change the State
    • Promise The object state of can only be modified once
  • then Method to execute the callback
    • Synchronize the execution of the task callback
    • Execution of asynchronous task callback
    • Specify multiple callbacks
    • Synchronous modification status then Method returns
    • Asynchronous modification state then Method returns
  • Promise Of API
    • Constructors : then,catch
    • Function object : resolve,reject,all,race Method

One 、 index.html

Test Manual promise.js

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./promise.js"></script>
</head>

<body>
    <script> let p = new Promise((resolve, reject) => {
       resolve('OK'); // reject("error"); // throw "err"; setTimeout(() => {
       // resolve('OK'); // reject('err'); // ............................ What should I do if I throw an error .............. // throw "err"; }, 1000); }); console.log(p); // p.then(value => {
       // console.log(value); // }, reason => {
       // console.warn(reason); // }) const res = p.then(value => {
       // alert(value); return 'hello'; // return new Promise((resolve, reject) => {
       // resolve("success"); // // reject("error"); // }) // throw "fail"; }, reason => {
       alert(reason); }) console.log(res); let res2 = p.catch(reason => {
       console.warn(reason); }) console.log(res2); //  extraordinary transmission , Value passed  p.then(value => {
       // console.log(111); // throw ' failed ' }).then(value => {
       console.log(222); }).then(value => {
       console.log(333); }).catch(reason => {
       console.warn(reason); }) // resolve Method test cases  const p1 = Promise.resolve('OK'); const p2 = Promise.resolve(new Promise((resolve, reject) => {
       reject("errpr"); })); const p3 = Promise.resolve(Promise.resolve('Oh Yeah!')); console.log(p1); // reject The test case  const r1 = Promise.reject('Error'); const r2 = Promise.reject(new Promise((resolve, reject) => {
       resolve('ok') })) console.log(r1); console.log(r2); //  call all Method  let a1 = new Promise((resolve, reject) => {
       resolve('OK'); }) let a2 = Promise.resolve('Success'); let a3 = Promise.resolve('Oh Yeah'); let result3 = Promise.all([a1, a2, a3]); console.log(result3); //  call race Method  let ra1 = new Promise((resolve, reject) => {
       setTimeout(() => {
       resolve('OK'); }) }) let ra2 = Promise.reject('Successs'); let ra3 = Promise.resolve('Oh Yeah!') let result4 = Promise.race([ra1, ra2, ra3]); console.log(result4); // then Asynchronous execution of method callback  let then1 = new Promise((resolve, reject) => {
       resolve('OK'); console.log(111); }) then1.then(value => {
       console.log(222); }) console.log(333); </script>
</body>

</html>

Two 、 promise.js

function Promise(executor) {
    
    //  Add attribute 
    this.PromiseState = 'pending';
    this.PromiseResult = null;
    //  Life attribute 
    this.callbacks = [];
    const self = this;

    // resolve function 
    function resolve(data) {
    
        // Promise Object state can only be modified once 
        if (self.PromiseState !== 'pending') return;
        // 1.  Modify the state of the object (promiseState)
        self.PromiseState = 'fulfilled';
        // 2.  Set the object result value (promiseResult)
        self.PromiseResult = data;
        //  Call the successful callback function 
        // if (self.callback.onResolved) {
    
        // self.callback.onResolved(data);
        // }
        setTimeout(() => {
    
            self.callbacks.forEach(item => {
    
                item.onResolved(item);
            })
        })
    }
    // reject function 
    function reject(data) {
    
        if (self.PromiseState !== 'pending') return;
        self.PromiseState = 'rejected';
        self.PromiseResult = data;
        //  Call the failed callback function 
        // if (self.callback.onRejected) {
    
        // self.callback.onRejected(data);
        // }
        setTimeout(() => {
    
            self.callbacks.forEach(item => {
    
                item.onRejected(data);
            })
        })
    }

    try {
    
        //  A synchronous invocation 【 Actuator functions 】
        executor(resolve, reject);
    } catch (e) {
    
        //  modify Promise The object status is failed 
        reject(e);
    }
}

//  add to then Method 
Promise.prototype.then = function(onResolved, onRejected) {
    
    const self = this;
    //  Determine the callback function parameters -> extraordinary transmission 
    if (typeof onRejected !== 'function') {
    
        onRejected = reason => {
    
            throw reason;
        }
    }
    if (typeof onResolved !== 'function') {
    
        onResolved = value => value;
        // value => { return value; }
    }
    return new Promise((resolve, reject) => {
    
        //  Packaging function 
        function callback(type) {
    
            try {
    
                //  Get the execution result of the callback function 
                let result = type(self.PromiseResult);
                //  Judge 
                if (result instanceof Promise) {
    
                    //  If it is Promise Object of type 
                    result.then(v => {
    
                        resolve(v);
                    }, r => {
    
                        reject(r);
                    })
                } else {
    
                    //  The object status of the result is success 
                    resolve(result);
                }
            } catch (e) {
    
                reject(e);
            }
        }
        if (this.PromiseState === 'fulfilled') {
    
            setTimeout(() => {
    
                callback(onResolved);
            })
        }
        if (this.PromiseState === 'rejected') {
    
            setTimeout(() => {
    
                callback(onRejected);
            })
        }
        //  Judge pending state 
        if (this.PromiseState === 'pending') {
    
            //  Save callback function 
            this.callbacks.push({
    
                onResolved: function() {
    
                    callback(onResolved);
                },
                onRejected: function() {
    
                    callback(onRejected);
                }
            })
        }
    })

}

//  add to  catch Method 
Promise.prototype.catch = function(onRejected) {
    
    return this.then(undefined, onRejected);
}

//  add to resolve Method 
Promise.resolve = function(value) {
    
    //  return promise object 
    return new Promise((resolve, reject) => {
    
        if (value instanceof Promise) {
    
            value.then(v => {
    
                resolve(v);
            }, r => {
    
                reject(r);
            })
        } else {
    
            resolve(value);
        }
    })
}

//  add to reject Method 
Promise.reject = function(reason) {
    
    return new Promise((resolve, reject) => {
    
        reject(reason);
    })
}

//  add to all Method 
Promise.all = function(promises) {
    
    //  The return result is promise object 
    return new Promise((resolve, reject) => {
    
        //  Declare variables 
        let count = 0;
        let arr = [];
        //  Traverse 
        for (let i = 0; i < promises.length; i++) {
    
            promises[i].then(v => {
    
                count++;
                arr[i] = v;
                if (count === promises.length) {
    
                    //  modify state 
                    resolve(arr);
                }
            }), r => {
    
                reject(r);
            }
        }
    })
}

//  add to  race  Method 
Promise.race = function(promises) {
    
    return new Promise((resolve, reject) => {
    
        for (let i = 0; i < promises.length; i++) {
    
            promises[i].then(v => {
    
                //  Modify the status of the returned object to [ success ]
                resolve(v);
            }, r => {
    
                reject(r);
            })
        }
    })
}

3、 ... and 、 Test return results display :

 Insert picture description here
 Insert picture description here

原网站

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