《尚硅谷Web前端Promise教程从入门到精通》系列博客_Promise自定义封装


前言

为学习axios打基础。本尚硅谷Web前端Promise教程从入门到精通系列博客内容介绍。
Promise是ES6引入的进行异步编程的新的解决方案,从语法上说它是一个构造函数,可以封装异步的任务,并且可以对结果进行处理。Promise最大的好处在于可以解决回调地狱的问题,并且在指定回调和处理错误方面更加灵活,在Web或者App项目中应用十分广泛,无论前端还是后端都可以看到Promise的身影,且是现在面试的高频题目,想进入一线大厂必须掌握Promise内部运行的原理。
尚硅谷Web前端Promise教程从入门到精通系列博客主要包含以下五部分:Promise 介绍与基本使用Promise APIPromise 关键问题Promise 自定义封装async 与await


Promise 自定义封装(手写Promise)

1.定义整体结构

下面html文件的代码是使用全局的Promise对象,由它实例出来的。

<!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>
</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,新建一个promise.js再用标签引进到html文件中。
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>

JS文件代码如下:根据上面代码的实参来填写下面的形参。

//声明构造函数
function Promise(executor){
   

}

//添加 then 方法
Promise.prototype.then = function(onResolved, onRejected){
   

}

2.resolve和reject结构搭建

//声明构造函数
function Promise(executor){
   
    //为了同步调用『执行器函数』,所以首先执行下面的代码。
    executor(resolve, reject);//但是这行代码的参数(两个函数)还没有定义,所以要定义出来,如下面的代码框中的代码所示
    
}

//添加 then 方法
Promise.prototype.then = function(onResolved, onRejected){
   

}
//声明构造函数
function Promise(executor){
   
    //resolve 函数
    function resolve(data){
   

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

    }

    //同步调用『执行器函数』
    executor(resolve, reject);
}

//添加 then 方法
Promise.prototype.then = function(onResolved, onRejected){
   

}

3.resolve和reject内部功能代码实现。

resolve()函数和reject()函数需要分别做两件事,修改Promise状态(需要添加这个属性)和设置Promise对象结果值(需要添加这个属性)。首先我们需要添加属性,再进行修改。

//声明构造函数
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){
   

}

4.throw抛出异常改变状态

我们需要想到,我们接收异常使用try、catch来实现。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Promise-封装 | 4 - throw 抛出异常改变状态 </title>
    <!-- <script src="./promise.js"></script> -->
</head>
<body>
    <script>
        let p = new Promise((resolve, reject) => {
     
            
            //抛出异常
            throw "error";
        });
        console.log(p);
    </script>
</body>
</html>
//声明构造函数
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;
    }
    try{
   
        //同步调用『执行器函数』
        executor(resolve, reject);
    }catch(e){
   
        //修改 promise 对象状态为『失败』
        reject(e);
    }
}

//添加 then 方法
Promise.prototype.then = function(onResolved, onRejected){
   

}

5.Promise对象状态只能改变一次

此时我们的代码在Html文件中的Promise对象可以填写resolve()和reject()两个,这样会导致Promise对象的状态被改变两次。
如下图所示:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Promise-封装 | 5 - 状态只能修改一次 </title>
    <script src="./promise.js"></script>
</head>
<body>
    <script>
        let p = new Promise((resolve, reject) => {
     
            reject("error");
            resolve('OK');
            //抛出异常
            // throw "error";
        });

        console.log(p);
    </script>
</body>
</html>

我们修改此bug后的JS代码如下:

//声明构造函数
function Promise(executor){
   
    //添加属性
    this.PromiseState = 'pending';
    this.PromiseResult = null;
    //保存实例对象的 this 的值
    const self = this;// self _this that
    //resolve 函数
    function resolve(data){
   
        //判断状态
        if(self.PromiseState !== 'pending') return;
        //1. 修改对象的状态 (promiseState)
        self.PromiseState = 'fulfilled';// resolved
        //2. 设置对象结果值 (promiseResult)
        self.PromiseResult = data;
    }
    //reject 函数
    function reject(data){
   
        //判断状态
        if(self.PromiseState !== 'pending') return;
        //1. 修改对象的状态 (promiseState)
        self.PromiseState = 'rejected';// 
        //2. 设置对象结果值 (promiseResult)
        self.PromiseResult = data;
    }
    try{
   
        //同步调用『执行器函数』
        executor(resolve, reject);
    }catch(e){
   
        //修改 promise 对象状态为『失败』
        reject(e);
    }
}

//添加 then 方法
Promise.prototype.then = function(onResolved, onRejected){
   

}

6.then()方法执行回调

//声明构造函数
function Promise(executor){
   
    //添加属性
    this.PromiseState = 'pending';
    this.PromiseResult = null;
    //保存实例对象的 this 的值
    const self = this;// self _this that
    //resolve 函数
    function resolve(data){
   
        //判断状态
        if(self.PromiseState !== 'pending') return;
        //1. 修改对象的状态 (promiseState)
        self.PromiseState = 'fulfilled';// resolved
        //2. 设置对象结果值 (promiseResult)
        self.PromiseResult = data;
    }
    //reject 函数
    function reject(data){
   
        //判断状态
        if(self.PromiseState !== 'pending') return;
        //1. 修改对象的状态 (promiseState)
        self.PromiseState = 'rejected';// 
        //2. 设置对象结果值 (promiseResult)
        self.PromiseResult = data;
    }
    try{
   
        //同步调用『执行器函数』
        executor(resolve, reject);
    }catch(e){
   
        //修改 promise 对象状态为『失败』
        reject(e);
    }
}

//添加 then 方法
Promise.prototype.then = function(onResolved, onRejected){
   
    //调用回调函数  PromiseState
    if(this.PromiseState === 'fulfilled'){
   
        onResolved(this.PromiseResult);
    }
    if(this.PromiseState === 'rejected'){
   
        onRejected(this.PromiseResult);
    }
}

7.异步任务回调的执行

html代码更改如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Promise-封装 | 7 - 异步任务 then 方法实现 </title>
    <script src="./promise.js"></script>
</head>
<body>
    <script>
        //实例化对象
        let p = new Promise((resolve, reject) => {
     
            setTimeout(() => {
     
                // resolve('OK');
                reject("error");
            }, 1000);
        });

        p.then(value => {
     
            console.log(value);
        }, reason=>{
     
            console.warn(reason);
        });

        console.log(p);
    </script>
</body>
</html>

分析:我们的then()函数需要在状态改变时才执行对应的回调函数,此时的then只是用来指定函数而不是执行,p.then(value => { console.log(value); }, reason=>{ console.warn(reason); });比如成功则执行value=>{console.log(value)},但看到我们是异步的,加入了setTimeout()函数,html文件运行到then()函数时,Promise对象的状态还没有改变,此时我们无法调用具体的函数,需要等到状态改变再调用。而只有通过resolve()函数或者reject()函数才可以改变状态,而在之前的代码中,resolve()函数或者reject()函数都不无法直接调用回调函数(因为作用域问题)。所以我们更改JS代码如下:

//声明构造函数
function Promise(executor){
   
    //添加属性
    this
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值