13

Promise对象

 3 years ago
source link: https://blog.csdn.net/All_bubbling/article/details/112165362
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Promise() 对象

了解promise对象之前我们要先了解回调地狱和如何解决回调地狱

  1. 回调地狱: 在使用JavaScript时,为了实现某些逻辑经常会写出层层嵌套的回调函数,如果嵌套过多,会极大影响代码可读性和逻辑,这种情况也被成为回调地狱
  2. 通过 Promise() 解决回调地狱

Promise() 基本实现流程(执行机制)

Promise对象是一个构造函数,用来生成Promise实例。

promise 的作用:Promise对象,可以将异步操作以同步操作的流程表达出来,避免了层层嵌套的回调函数。此外,Promise对象提供统一的接口,使得控制异步操作更加容易。

promise 接受一个函数作为参数: 函数有两个参数: resolve(成功) reject(失败); 他们两个是函数,由 JavaScript 引擎提供,不用自己部署。

Resolve函数的作用是,将Promise对象的状态从“未完成”变为“成功”(即从 pending 变为 resolved),在异步操作成功时调用,并将异步操作的结果,作为参数传递出去;

Reject函数的作用是,将Promise对象的状态从“未完成”变为“失败”(即从 pending 变为 rejected),在异步操作失败时调用,并将异步操作报出的错误,作为参数传递出去。

promise 的状态: 有三种状态:pending(进行中)、fulfilled(已成功)和rejected(已失败)。

Promise对象的状态改变,只有两种可能:从pending变为fulfilled和从pending变为rejected。 当处于pending状态时,无法得知目前进展到哪一个阶段

Promise() ()基本代码逻辑

let flag = true;
function fun(){
    return new Promise( (resolve, reject) =>{
        if(flag){
            // resolve() 代表成功, resolve() 调用执行 then() 中的回调函数
            // resolve()
            //  参数 result 就是传递的数据  需要通过then() 中回调函数接受
            resolve(result) 
        }else{
            //  reject() 代表失败, reject() 调用执行 catch() 中的回调函数
            // reject()
            //  参数 error 就是传递的错误信息 需要通过catch() 中回调函数接受
            reject(error)
        }
    })
}

// fun().then(() => {}).catch(() => {})

fun().then((data) => {}).catch((err) => {})

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK