PROMISE基础语法

2022-10-30 09:26:59

Promise是用来解决js中的异步编程问题

let p1 = new Promise([executor])
new Promise 创建 Promise 的实例时 一定要传一个executor函数
new 的时候首先第一件事情就是把[executor]函数执行
会给[executor]函数传递两个实参信息:resolve函数 和 reject函数

Promise状态status/Promise value

new Promise的时候,初始状态是(status):pending   value:undefined
resolve函数执行    status:fulfilled/resolved   value:传递的第一个实参
reject函数执行     status:rejected             value:传递的第一个实参

一旦状态改为成功或者失败,则当前操作不可逆转,状态就确定下来了,不能再改变为其他的状态

Promise.prototype上存在三个方法: then() catch() finally()
[then] 方法
基于then方法我们可以向当前的实例对应的 “事件池” 中存放0到2个方法,如果Promise的状态变为成功,会把then中存放的第一个方法执行,如果状态是失败,则then中存放的第二个方法执行;不论执行那个方法都会把value值传递给方法
then只是往事件池中里加方法,只有触发resolve方法或者reject方法 才会执行
每一次执行then方法都会返回一个新的Promise实例
在这里插入图片描述

let p1=newPromise((resolve, reject)=>{
	console.log(1, resolve, reject);// 一般会在这里管控一个异步编程操作setTimeout(()=>{resolve(10)},1000)
	console.log("19");})// 每一次执行then方法都会返回一个新的Promise实例// P2实例的状态成功还是失败,以及它的value值,由p1事件池中的方法执行决定// 1、不论执行的是A(P1池子中成功的函数)还是B(P1池子中失败的函数),只要代码执行不报错,不抛出异常信息等,则P2的状态都会变为成功态;A或者B执行的的返回结果,是P2实例的value值(如果报错,则报错信息是value值)// 2、如果A或者B执行没有报错,但是返回结果是一个新的Promise实例,则需要等待新的Promise实例有结果,用这个结果代替P2的结果// Promise.resolve(100)、Promise.reject(100)返回成功或者失败状态的Promise实例let p2= p1.then(result=>{
	console.log('resolved', result);return100}, reason=>{
    console.log('rejected', reason);return200})

p2.then(result=>{
    console.log('resolved', result);}, reason=>{
    console.log('rejected', reason);})
  • 作者:十里顾情欢
  • 原文链接:https://blog.csdn.net/qq_45368052/article/details/106650125
    更新时间:2022-10-30 09:26:59