Promise

Promise

// Promise就是解决回调地狱

`注意点`
1.resolve,reject里面回调函数的参数,可以随便起名,但是建议大家使用这两个单词

2.resolve成功 函数   当成功时可以调用resolve函数 resolve()
3.reject失败 函数  当失败时可以调用reject函数 reject()

4.在promise中,只能同时执行一个resolve或者reject,不能执行两个或以上且resolve和reject不能同时执行
5.在Promise中有一个状态机制 
      pending   如果当前Promise没有执行resolve或者reject时,状态为pending,挂起状态
      fulfilled 如果当执行了resolve,当前状态就会变为fulfilled,意味着成功了
      rejected  如果当执行了reject时,当前状态变为rejected,意味着失败了

6.当执行resolve或者reject,首先会判断当前状态是否是pending,如果是就会执行并且修改当前状态为对应的状态  如果当前状态不是pending状态,就会放弃执行resolve或者reject

7.resolve和reject都可以传参,但是只能传一个参数


	var p = new Promise(function (resolve, reject) {
      resolve("aaa")
      reject("bbb")
    })
    //方式1
    // 当执行了resolve,就会调用then中function函数
    // 如果执行了reject 就会调用catch中function函数
    p.then(function (a) {
      console.log(a)
    }).catch(function (b) {
      console.log(b)
    })

    //方式2
    // then中第一个函数是resolve执行时调用,第二个函数是reject时调用
    p.then(function (a) {
      console.log(a)
    }, function (b) {
      console.log(b)
    })

链式结构

//p.then().then().then()....
	var p = new Promise(function (resolve, reject) {
      resolve();
    })
    p.then(function () {
      console.log("a");
      return new Promise(function (resolve, reject) {
        resolve();
      }).then(function () {
        console.log("b")
      })
    })
//红绿灯
    function showLight(light, time) {
      return new Promise(function (resolve, reject) {
        setTimeout(function () {
          console.log(light);
          resolve();
        }, time)
      })
    }

    function show() {
      showLight("红灯", 3000).then(function () {
        return showLight("黄灯", 1000);
      }).then(function () {
        return showLight("绿灯", 2000)
      }).then(function () {
        show();
      })
    }
    show();
//图片加载
	function loadImage(src) {
      return new Promise(function (resolve, reject) {
        var img = new Image();
        img.src = src;
        img.onload = function () {
          resolve(img);
        };
        img.onerror = function () {
          reject(src);
        }
      })
    }

    var arr = [];
    loadImage("./img/2-.jpg").then(function (img) {
      arr.push(img);
      return loadImage("./img/3-.jpg")
    }).then(function (img) {
      arr.push(img);
      return loadImage("./img/4-.jpg")
    }).then(function (img) {
      arr.push(img);
      return loadImage("./img/5-.jpg")
    }).then(function (img) {
      arr.push(img);
      return loadImage("./img/6-.jpg")
    }).then(function (img) {
      arr.push(img);
      return loadImage("./img/7-.jpg")
    }).then(function (img) {
      arr.push(img);
      return loadImage("./img/8-.jpg")
    }).then(function (img) {
      arr.push(img);
      console.log(arr);
    })

一些方法

1.Promise.resolve()
	Promise.resolve().then(function () {
      console.log("aa")
    })
    //上面的方法等同于下面的
    new Promise(function (resolve, reject) {
      resolve();
    }).then(function () {
      console.log("aa")
    })

2.Promise.reject()
	Promise.reject().then(function () {
      console.log("aa")
    })
	//上面的方法等同于下面的
	new Promise(function (resolve, reject) {
      reject();
    }).catch(function () {
      console.log("aa")
    })

3.Promise.all()
	//将若干个Promise对象组成的数组放在all中,这Promise.all方法将会把每个Promise执行resolve后返回的参数放在一个新的数组  通过then返回每个Promise中resolve返回值组成的数组    如果有一个错误就执行catch
	// Promise.all 中所有的内容是一起运行的
'应用'
	var arr = [];
    for (var i = 2; i < 48; i++) {
      arr.push(loadImage("./img/" + i + "-.jpg"))
    }

    Promise.all(arr).then(function (list) {
      console.log(list)
      list.forEach(item => console.log(item.src))
    }).catch(function () {
      console.log("aaa")
    })
4.Promise.allSettled()
//不管是否成功或者失败,全部执行完成后都会进入then 执行
'二者区别:区别在于它们处理Promise数组中失败项的方式不同'
1)Promise.all在全部成功时才返回,一旦有Promise被拒绝,立即返回拒绝的Promise。
2)Promise.allSettled会等待所有Promise都完成(无论成功与否),并以一个包含每个Promise结果的对象数组的形式返回
	结果的对象数组中	
    每个对象具有status和value属性:
status可为字符串"fulfilled"表示成功、或字符串"rejected"表示拒绝。
value属性存储了已解决或已拒绝的值。

5.Promise.race() 赛跑
返回一个Promise
哪个先执行resolve,就直接执行then(即谁是对的谁先返回)
6.Promise.any() 赛跑
'二者的区别:
race如果第一个先出错,就不会执行then
any第一个出错就会放弃,继续第二个尝试如果完成直接执行then返回第二个结果

7.Promise.withResolvers() 2024新增属性
// 从Promise中抽出promise对象,resolve,reject函数
	var { promise, resolve, reject } = Promise.withResolvers();
    setTimeout(function () {
      console.log("aa");
      resolve();
    }, 3000)
// 当执行resolve函数后,
// promise对象的then方法就会被执行
    promise.then(function () {
      console.log("bb")
    })

async和await

//普通函数
    function fn() {

    }

//异步函数
    async function fn() {

    }

//生成器函数
    function* fn() {

    }

async

	//async函数执行后返回一个Promise对象
    //return的结果必须使用then接收
    async function fn() {
      return 10;
    }
    var a = fn();
    console.log(a)//Promise {<fulfilled>: 10}
    //要使用then接收
    a.then(function (value) {
      console.log(value)//10
    })

await

//await 等待 只能等待Promise对象的resolve
	1.await必须写在async函数中
	2.只能等待promise对象的resolve (只有使用promise 才能使用async)
	3.await返回的值就是resolve传入的参数
	4.await在使用时后面要写一个catch 解决reject的问题
	5.promise正确的 执行resolve的结果返回变量,错误的将会执行catch
//红绿灯
	//await 等待 只能等待Promise对象的resolve
    function showLight(light, time) {
      return new Promise(function (resolve, reject) {
        setTimeout(function () {
          console.log(light);
          resolve();
        }, time)
      })
    }

    async function fn() {
      // 添加await之后 造成阻塞等待
      await showLight("红灯", 3000);
      await showLight("黄灯", 1000);
      await showLight("绿灯", 2000);
    }//执行顺序 红 黄 绿(同步)
	//不加await时的执行顺序 黄 绿 红(异步)
    fn();
//加载图片
	function loadImage(src) {
      return new Promise(function (resolve, reject) {
        var img = new Image();
        img.src = src;
        img.onload = function () {
          resolve(img);
        };
        img.onerror = function () {
          reject(src);
        }
      })
    }

    async function fn() {
      var arr = [];
      for (var i = 0; i < 90; i++) {
//promise正确的执行resolve的结果返回变量img,错误的将会执行catch
        var img = await loadImage(`./img/${i}-.jpg`).catch(info => console.log(info));
        if (img) arr.push(img)
      }
      arr.forEach(item => console.log(item.src));
    }
    fn();

异步

// 异步:如果不希望在这里等待加载,希望这里加载的同时,继续向后执行后面的html 
    // setTimeout
    // setInterval
    // οnlοad=function(){}
    // οnerrοr=function(){}

    console.log("a")
    setTimeout(function () {
      console.log("b")
    }, 3000)
    console.log("c")
    //正常是 a c b
    //若希望等待3秒后,打印b以后再继续向后执行打印c 就是阻塞式同步

`所有的异步都不参与到同步事件当中`
    
    
`JS中的异步操作是:借用浏览器的多线程机制,再基于EventLoop事件循环机制,实现的单线程异步效果!!`
每次打开一个浏览器页面打开一个进程 在这个进程中会有很多线程

同步

//同步:当默认状态时,js加载先加载完成一个文件后,执行js后才会继续向后执行
    console.log(Date.now());
    var time = Date.now();
    for (var i = 0; i < 1000000000; i++) {

    }
    console.log(Date.now() - time);//时间差

事件轮询(面试重点)

同步任务在第一次事件轮询中全部完成
异步任务不会在第一次事件轮询中全部完成,就有了下面的微任务和宏任务

微任务和宏任务
	'微任务':
		Promise的then或者catch 
		asyncawait部分
		process.nextTick(()=>{})(nodejs中)
	'宏任务':
		setTimeout 
		setInterval 
		setImmediate(nodejs中)闲时执行
    
        setTimeout(function(){
	//不写时间 默认在同步任务完成的下一帧运行
	})    

/*
遇到微任务,将放在当前任务列的最下面执行
遇到宏任务,时间达到时,新建一个任务列,放在这个新建任务列的最顶部执行*/

    console.log("A")
    new Promise(function (resolve, reject) {
      resolve();
      console.log("B")
    }).then(function () {
      console.log("C")
    })
    console.log("D")
    //执行顺序是 A B D C


	setTimeout(function () {
      console.log("B");
    })
    Promise.resolve().then(function () {
      console.log("A")
    })
    console.log("C")
    //执行顺序是 C A B
//setTimeout开辟了新任务列,且在新任务列最顶端,Promise.resolve是微任务放在当前任务列的最底部
   Promise.resolve().then(function () {
      setTimeout(function () {
        console.log("A")
      })
    })
    setTimeout(function () {
      Promise.resolve().then(function () {
        console.log("B")
      })
    })
    //执行顺序是 B A
事件轮询1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值