Promise从入门到自定义之手写Promise(前端进阶必学)

promise前端进阶

一、准备工作

1、区别实例对象跟函数对象

  • 函数对象:将函数作为对象使用时
  • 实例对象:new 函数生产的对象

function Fn(){} //Fn函数

const fn = new Fn() //Fn是构造函数 fn是实例对象

Fn.prototype //Fn是函数对象

Fn.call({}) //Fn是函数对象

$('#test') //jQuery函数

$.get('/') //jQuery函数对象

总结:点的左边是对象,括号的左边是函数

2、回调函数的分类

同步回调

立即执行,完全执行完了才结束,不会放入回调队列

例子:数组遍历相关的回调函数、promise的excutor函数

// 同步回调
const arr=[1,2,3]
arr.forEach(item =>{
	console.log(item)
})
console.log('forEach后')
/*
运行结果:
1 
2 
3 
forEach后
*/
异步回调

不立即执行,会放入回调队列中将来执行

例子:定时器回调、ajax回调、promise的成功失败

// 异步回调
setTimeout(arr=>{
	console.log('arr')
},0)
console.log('setTimeout之后')
/*
运行结果:
setTimeout之后 
arr
*/

3、error错误处理

错误的类型

  • Error:所有错误的父类型
  • ReferenceError:引用的变量不存在
  • TypeError:数据类型不正确的错误
  • SyntaxError:语法语法

捕获错误:try...catch

抛出错误:throw error

错误对象

  • message属性:错误相关信息
  • stack属性:函数调用栈记录信息

二、promise的理解与使用

1、promise是什么

理解
  • 抽象表达:

    promise是js中异步编程的新的解决方案

  • 具体表达:

    1. promise是一个构造函数
    2. promise对象用来封装一个异步操作并可以获取其结果
promise的状态改变
  1. pending变为resolved

  2. pending变为rejected

    只有这2种,且一个promise对象只能改变一次无论失败还是成功

    成功一般称为value,失败称为reason

工作原理图

使用流程实例
<script>
        // 1.创建一个新的promise对象
        const p = new Promise((resolve,reject)=>{
    
        // 2.执行异步操作任务
            const time = Date.now()//偶数成功,奇数失败
        // 3.1如果成功,调用resolve(value)
            if(time %2 == 0){
    
                resolve('成功的数据,time='+time)
            }else {
    
            // 3.2如果失败,调用reject(reason)
                reject('失败的数据,time='+time)
            }
        
        })
        p.then(
            value => {
    //接受到的成功value数据
                console.log('成功的个回调',value)
            },
            reason =>{
    //接受到失败的reason数据
                console.log('失败的回调',reason)
            }
        )
    </script>

2、为什么用promise

指定回调函数的方式更加灵活

因为没用Promise之前,使用回调函数时,传入的回调函数必须放在前面,放到后边就用不到了,导致得不到数据

  • 旧的:说白了原来的方式就是必须在启动异步任务前指定

  • promise:启动异步任务=》返回promise对象=》给promise对象绑定回调函数(甚至可以在异步)

支持链式调用,可以解决回调地狱

回调地狱

回调函数嵌套调用,外部回调函数异步执行的结果是嵌套的回调函数执行的条件

doSomething(function (result) {
     doSomethingElse(result, function (newResult) {
         doThirdThing(newResult, function (finalResult) {
             console.log('Got the final result: ' + finalResult)
         }, failureCallback)
     },failureCallback)
 }, failureCallback)

promise解决回调地狱

一个promise对应一个异步结果

doSomething()
.then( function( result) {
return doSomethingElse(result)
})
.then( function(newResult) {
return doThirdThing( newResult)
})
.then( function(finalResult) {
console.log('Got the final result: ' + finalResult)
})
.catch( failureCallback) 

async / await: 回调地狱的终极解决方案

async function request() {
    try {
        const result = await doSomething()
        const newResult = await doSomethingElse(result)
        const finalResult = await doThirdThing(newResult)
        console.log('Got the final result: ' + finalResult)
    } catch (error) {
        failureCallback(error)
    }
}

3、如何使用promise

API
  1. Promise构造函数:

    Promise (excutor) {}

  • excutor函数:同步执行(resolve, reject) => {}

  • resolve函数:内部定义成功时我们调用的函数value => { }

  • reject函数:内部定义失败时我们调用的函数reason => {}

    说明: excutor 会在Promise内部立即同步回调,异步操作在执行器中执行

  1. Promise.prototype.then方法: ``(onResolved, onRejected) => {}
  • onResolved函数:成功的回调函数(value) => {}

  • onRejected函数:失败的回调函数(reason) => {}

    说明:指定用于得到成功value的成功回调和用于得到失败reason的失败回调
    返回一个新的promise对象

  1. Promise.prototype.catch方法:(onRejected) => {}`
  • onRejected函数:失败的回调函数(reason) => {}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值