zoukankan      html  css  js  c++  java
  • Promise嵌套问题/async await执行顺序

    /*
    原则:
    执行完当前promise,
    会把紧挨着的then放入microtask队尾,
    链后面的第二个then暂不处理分析,
    */
    一、
    new Promise((resolve, reject) => {
      console.log("promise1")
      resolve()
    }).then( () => {
      console.log("then11")
      new Promise((resolve, reject) => {
      console.log("promise2")
      resolve()
      }).then(() => {
      console.log("then21")
      }).then(() => {
        console.log("then23")
        })
    }).then(() => {
    console.log("then12")
    })



    1.先执行同步部分代码输出 "promise1"
    2.第一个then执行, 产生了promise对象, 放到microtask里(第二个then必须要等要第一个then产生的promise同步部分执行完才能放到队列里)
    3.then方法构建了一个promise, 同步代码中输出 then11
    4.then方法里又新建了promise 执行同步部分 输出promise2, 把第一个then放到microtask里, 把外面的then放到microtask里
    5.取出microtask, 输出then21,然后里面第二个then进入microtask, 输出then12
    6.输出then23




    二、
    new Promise((resolve, reject) => {
      console.log("promise1")
      resolve()
    }).then(() => {
      console.log("then11")
      new Promise((resolve, reject) => {
      console.log("promise2")
      resolve()
      }).then(() => {
      console.log("then21")
      }).then(() => {
      console.log("then23")
      })
    }).then(() => {
    console.log("then12")
    })
     
    new Promise((resolve, reject) => {
    console.log("promise3")
    resolve()
    }).then(() => {
    console.log("then31")
    })
     
    1.执行外层Promise同步代码
    输出promise1 第一个then进入microtask队列,第二个then不进入(因为这个要等第一个then产生的promise初始化完)
    2.输出promise3,最下面的then进队列
    此时队列中
    ----出口方向--->
    [then31],[then1]
    3.执行then1 输出了then11 构造了一个新的promise,执行同步代码promise2 then21进入队列,then12进入队列
    ---出口方向-->
    [then12],[then21],[then31]
    4.输出then31,then21,此时最后一个then,then23进入队列
    ---出口方向->
    [then23],[then12],[then21]
    输出 then21, then12, then23




    三、
    async/await
    async function async1() {
    console.log("async1 start");
    await async2();
    console.log("async1 end");
    }
    async function async2() {
    console.log( 'async2');
    }
    console.log("script start");
    setTimeout(function () {
    console.log("settimeout");
    },0);
    async1();
    new Promise(function (resolve) {
    console.log("promise1");
    resolve();
    }).then(function () {
    console.log("promise2");
    });
    console.log('script end');



    //script start,async1 start,async2,promise1,script end,async1 end,promise2,settimeout
    // 处理这种问题的方法:await后面跟的是一个promise对象。如果await函数,那么这个函数里的部分就应该同步执行,
    // await下面的语句相当于promise.then里面的语句。
  • 相关阅读:
    DNS服务器出错造成“不知道这样的主机”
    downadup.B蠕虫病毒处理手记
    今天新接触到一个名词——GSV
    客户端获取SQL服务端的MAC
    关于SQL事务的测试
    ftp://ftp.microsoft.com
    AJAX.DLL的使用
    "界面规则层与业务规则层"让我想开了
    客户端cookie也会传到服务端的Request.Params?
    Ext.Fx
  • 原文地址:https://www.cnblogs.com/eret9616/p/10891581.html
Copyright © 2011-2022 走看看