1. 程式人生 > 其它 >promise自定義封裝

promise自定義封裝

初始結構搭建:

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Promise-封裝 | 1 - 初始結構搭建</title>
    <script src="./promise.js"></script>
</
head> <body> <script> let p = new Promise((resolve, reject) => { resolve('OK'); }); p.then(value => { console.log(value); }, reason=>{ console.warn(reason); }) </script> </body> </
html>

promise.js:

function Promise(executor){

}

//新增 then 方法
Promise.prototype.then = function(onResolved, onRejected){

}





resolve與reject結構搭建:

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0"
> <title>Promise-封裝 | 2 - resolve 與 reject </title> <script src="./promise.js"></script> </head> <body> <script> let p = new Promise((resolve, reject) => { resolve('OK'); }); p.then(value => { console.log(value); }, reason=>{ console.warn(reason); }) </script> </body> </html>

promise.js:

//宣告建構函式
function Promise(executor){
    //resolve 函式
    function resolve(data){

    }
    //reject 函式
    function reject(data){

    }

    //同步呼叫『執行器函式』
    executor(resolve, reject);
}

//新增 then 方法
Promise.prototype.then = function(onResolved, onRejected){

}






3-resolve與reject函式實現

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Promise-封裝 | 2 - resolve 與 reject </title>
    <script src="./promise.js"></script>
</head>
<body>
    <script>
        let p = new Promise((resolve, reject) => {
            // resolve('OK');
            reject("error");
        });

        console.log(p);

        // p.then(value => {
        //     console.log(value);
        // }, reason=>{
        //     console.warn(reason);
        // })
    </script>
</body>
</html>

promise.js:

//宣告建構函式
function Promise(executor){
    //新增屬性
    this.PromiseState = 'pending';
    this.PromiseResult = null;
    //儲存例項物件的 this 的值
    const self = this;// self _this that
    //resolve 函式
    function resolve(data){
        //1. 修改物件的狀態 (promiseState)
        self.PromiseState = 'fulfilled';// resolved
        //2. 設定物件結果值 (promiseResult)
        self.PromiseResult = data;
    }
    //reject 函式
    function reject(data){
        //1. 修改物件的狀態 (promiseState)
        self.PromiseState = 'rejected';// 
        //2. 設定物件結果值 (promiseResult)
        self.PromiseResult = data;
    }

    //同步呼叫『執行器函式』
    executor(resolve, reject);
}

//新增 then 方法
Promise.prototype.then = function(onResolved, onRejected){

}