【Promise】前端学习记录16

【Promise】前端学习记录16,第1张

抽象表达
promise是一门新的技术(ES6规范)
是JS中进行异步编程的新解决方案(旧方案是单纯的使用回调函数)具体表达
从语法上来看:promise是一个构造函数
从功能上看:promise对象用来封装一个异步 *** 作并可以获取其成功/失败的结果值特点
指定回调的方式更加灵活
支持链式调用,可以解决回调地域问题
util.promisify

传入一个遵循常见错误优先的回调风格的函数(即以(err, value) => …回调作为最后一个参数),并返回一个返回promise的版本

const fs = require('fs');
const util = require('util');
const mineReadfile = util.promisify(fs.readFile);
mineReadfile('./....txt').then( );
promise的状态

实例对象中的一个属性 PromiseState
pending
resolved/fullfilled
rejected
只有两种变化 pending=>resolved 或者 pending=>rejected

promise对象的值

实例对象的另一个属性 promiseResult
保存着异步任务成功/失败的结果
resolve()
reject()

工作流程

API Promise构造函数:promise(excutor){}
excutor函数:执行器(resolve, reject)=>{}
excutor会在promise内部立即同步调用promise.prototype.thenPromise.prototype.catch只能执行失败的回调Promise.resolve 函数对象的方法:value =>{}
返回一个成功/失败的promise对象Promise.reject 函数对象的方法:value =>{}
返回一个失败的promise对象promise.all方法:(promises)=>{}promise.race方法:(promises)=>{}
返回一个新的promise,第一个完成promise的结果状态就是最终的状态 关键问题 如何改变promise对象的状态
resolve reject throw一个promise指定多个成功/失败回调函数,都会调用吗
当promise改变为对应状态时都会调用改变promise状态和then指定回调函数谁先谁后
都有可能,正常情况下是先指定回调再改变状态,但也可以先改变状态再指定回调
如何先改变状态后指定回调:在执行器中直接调用reslove()/reject();延迟更长的时间在调用then方法promise.then()返回的新promise的结果状态由什么决定
简单表达:由then()指定的回调函数执行的结果决定promise如何串联多个 *** 作任务
promise的then()返回一个新的promise,可以看成then()的链式调用promise异常穿透
当时用promise的then链式调用,可以在最后指定失败的回调,前面任何 *** 作出现了异常,都会传到最后失败的回调中处理如何中断promise链
在回调函数中返回一个pendding状态的promise对象
return new Promise(() =>())
自定义封装-手写promise

过程:
初始结构搭建

function Promise(executor) {
}

Promise.prototype.then = function(onResolved, onReject){
}

resolve和reject结构搭建

function Promise(executor) {
	function resolve(data){
	}
	function resolve(data){
	}
    executor(resolve, reject);
}

Promise.prototype.then = function(onResolved, onReject){
}

resolve和reject代码实现

function Promise(executor) {
	this.PromiseState = 'pending';
	this.PromiseResult = null;
	self = this;
	function resolve(data){
		self.PromiseState = 'fulfilled'
		self.PromiseResult = data;
	}
	function resolve(data){
		self.PromiseState = 'rejected'
		self.PromiseResult = data;
	}
    executor(resolve, reject);
}

Promise.prototype.then = function(onResolved, onRejected){
}

throw抛出异常改变状态

try catch处理throw抛出的异常

function Promise(executor) {
	this.PromiseState = 'pending';
	this.PromiseResult = null;
	self = this;
	function resolve(data){
		self.PromiseState = 'fulfilled'
		self.PromiseResult = data;
	}
	function resolve(data){
		self.PromiseState = 'rejected'
		self.PromiseResult = data;
	}
	try{
    	executor(resolve, reject);
    }catch(e){
    	reject(e);
    }
}

Promise.prototype.then = function(onResolved, onRejected){
}

Promise对象状态只能修改一次

function Promise(executor) {
	this.PromiseState = 'pending';
	this.PromiseResult = null;
	self = this;
	function resolve(data){
		if(PromiseState != 'pending') return;
		self.PromiseState = 'fulfilled'
		self.PromiseResult = data;
	}
	function resolve(data){
		if(PromiseState != 'pending') return;
		self.PromiseState = 'rejected'
		self.PromiseResult = data;
	}
	try{
    	executor(resolve, reject);
    }catch(e){
    	reject(e);
    }
}

Promise.prototype.then = function(onResolved, onRejected){
}

then方法执行回调

function Promise(executor) {
	this.PromiseState = 'pending';
	this.PromiseResult = null;
	self = this;
	function resolve(data){
		if(PromiseState != 'pending') return;
		self.PromiseState = 'fulfilled'
		self.PromiseResult = data;
	}
	function resolve(data){
		if(PromiseState != 'pending') return;
		self.PromiseState = 'rejected'
		self.PromiseResult = data;
	}
	try{
    	executor(resolve, reject);
    }catch(e){
    	reject(e);
    }
}

Promise.prototype.then = function(onResolved, onRejected){
	if(this.PromiseState === 'fulfilled'){
        onResolved(this.PromiseResult);
    }
    if(this.PromiseState === 'rejected'){
        onRejected(this.PromiseResult);
    }
}

then方法回调的异步执行

function Promise(executor) {
	this.PromiseState = 'pending';
	this.PromiseResult = null;
	this.callback = {};
	self = this;
	function resolve(data){
		if(PromiseState != 'pending') return;
		self.PromiseState = 'fulfilled'
		self.PromiseResult = data;
		if(self.callback.onResolved){
            self.callback.onResolved(data);
        }
	}
	function resolve(data){
		if(PromiseState != 'pending') return;
		self.PromiseState = 'rejected'
		self.PromiseResult = data;
		if(self.callback.onRejected){
            self.callback.onRejected(data);
        }
	}
	try{
    	executor(resolve, reject);
    }catch(e){
    	reject(e);
    }
}

Promise.prototype.then = function(onResolved, onRejected){
	if(this.PromiseState === 'fulfilled'){
        onResolved(this.PromiseResult);
    }
    if(this.PromiseState === 'rejected'){
        onRejected(this.PromiseResult);
    }
    if(this.PromiseState === 'pending'){
        this.callback = {
            onResolved: onResolved,
            onRejected: onRejected
        }
    }
}

指定多个回调的实现

将callback存储为数组,记录每一个需要回调的函数
执行时挨个执行

同步和异步修改then方法

   if(this.PromiseState === 'pending'){
            this.callbacks.push({
                onResolved: function(){
                    try{
                        let result = onResolved(self.PromiseResult);
                        if(result instanceof Promise){
                            result.then(v => {
                                resolve(v);
                            }, r => {
                                reject(r)
                            })
                        } else {
                            resolve(result)
                        }
                    }catch(e){
                        reject(e);
                    }           
                },
                onRejected: function(){
                    try{
                        let result = onRejected(self.PromiseResult);
                        if(result instanceof Promise){
                            result.then(v => {
                                resolve(v);
                            }, r => {
                                reject(r)
                            })
                        } else {
                            resolve(result)
                        }
                    }catch(e){
                        reject(e);
                    }
                    
                }
            })
        }

then方法完善与优化
catch方法-异常穿透
resolve方法封装
reject方法封装
all方法封装
race方法封装
then方法回调的异步执行

class Promise{
    constructor(executor){
            //添加属性
        this.PromiseState = 'pending';
        this.PromiseResult = null;
        //声明属性
        this.callbacks = [];
        //保存实例对象的this值
        const self = this;
        //resolve函数
        function resolve(data){
            if(self.PromiseState != 'pending') return;
            //修改对象状态 promisestate
            //修改对象结果值 promiseResult
            self.PromiseState = 'fulfilled';
            self.PromiseResult = data;
            setTimeout(()=>{
                self.callbacks.forEach(items => {
                    items.onResolved(data);
                })
            })
        }
        //reject函数
        function reject(data){
            //判断状态
            if(self.PromiseState != 'pending') return;
            //修改对象状态 promisestate
            //修改对象结果值 promiseResult
            self.PromiseState = 'rejected';
            self.PromiseResult = data;
            setTimeout(()=>{
                self.callbacks.forEach(items => {
                    items.onRejected(data);
                })
            })
        }
        try{
            //同步调用 执行器函数
            executor(resolve, reject);
        }catch(e){
            //修改promise的状态设置为失败
            reject(e);
        }
        

    }
    then(onResolved, onRejected){
        const self = this;
        if(typeof onRejected !== 'function'){
            onRejected = reason => {
                throw reason;
            }
        }
        if(typeof onResolved !== 'function'){
            onResolved = value => value;
        }
        return new Promise((resolve, reject) =>{
            function callback(type){
                try{
                    let result = type(self.PromiseResult);
                    if(result instanceof Promise) {
                        result.then(v=>{
                            resolve(v)
                        }, r=>{
                            reject(r)
                        })

                    }else{
                        resolve(result)
                    }

                }catch(e){
                    reject(e)
                }
            }
            if(this.PromiseState === 'fulfilled'){
                setTimeout(()=>{
                    callback(onResolved);
                });
                            
            }
            if(this.PromiseState === 'rejected'){
                setTimeout(()=>{
                    callback(onRejected);
                })
            
            }
            //判断pending的状态
            if(this.PromiseState === 'pending'){
                this.callbacks.push({
                    onResolved: function(){
                        callback(onResolved);       
                    },
                    onRejected: function(){
                        callback(onRejected);
                    }
                })
            }

        })

    }
    catch(onRejected){
        return this.then(undefined, onRejected)
    }
    static resolve(value){
        return new Promise((resolve, reject) => {
            if(value instanceof Promise){
                value.then(v=>{
                    resolve(v);
                }),r=>{
                    reject(r);
                }
            }else{
                resolve(value);
            }
    
        })
    }
    static reject(reason){
        return new Promise((resolve, reject)=>{
            reject(reason);
        })
    }
    static all(promises){
        return new Promise((resolve, reject)=>{
            //声明变量
            let count = 0
            let arr = [];
            for(let i = 0; i<promises.length; i++){
                promises[i].then(v =>{
                    //得知对象的状态是成功
                    count++;
                    arr[i] = v;
                    if(count === promises.length){
                        resolve(arr);
                    }
                }, r=>{
                    reject(r);
                }
                )
            }
        })
    
    }
    static race(promises){
        return new Promise((resolve, reject)=>{
            for(let i = 0; i < promises.length; i++){
                promises[i].then(v=>{
                    resolve(v);
                },r=>{
                    reject(r);
                }
                )
            }
        })
    }
}
async函数 函数的返回结果为promise对象promise对象的结果由async函数执行的返回值决定和then方法的返回结果的规则是一样的
async function main(){
}

let result = main();
console.log(result)
await函数 await右侧的表达式一般为promise对象,但也可以是其他的值如果表达式是promise对象,await返回的值是promise成功的值如果表达式是其他值,直接将此值作为await的返回值 await必须写在async函数中,但async函数中可以没有await如果await的promise失败了,就会抛出异常,需要通过try…catch捕获处理

async和await结合

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/944883.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-18
下一篇 2022-05-18

发表评论

登录后才能评论

评论列表(0条)

保存