美文网首页
微任务执行顺序

微任务执行顺序

作者: 苍老师的眼泪 | 来源:发表于2022-04-18 23:52 被阅读0次

    第一题:
    链式Promise

        new Promise((resolve, reject) => {
          console.log(1)
          resolve()
        }).then(() => {
          console.log(2)
          new Promise((resolve, reject) => {
            console.log(3)
            resolve()
          }).then(() => {
            console.log(4)
          }).then(() => {
            console.log(5)
          })
        }).then(() => {
          console.log(6)
        })
    
        new Promise((resolve, reject) => {
          console.log(7)
          resolve()
        }).then(() => {
          console.log(8)
        })
    
      // 执行结果:1,7,2,3,8,4,6,5
    

    第二题:
    async / await

        setTimeout(() => {
          console.log(1)
        }, 100)
    
        setTimeout(() => {
          console.log(2)
        }, 0)
    
        Promise.resolve(console.log(3)).then(() => { console.log(4) })
    
        async function async1() {
          console.log(5)
          await async2()
          console.log(6)
        }
    
        async function async2() {
          console.log(7)
        }
    
        async1()
    
        // 结果:3, 5, 7, 4, 6, 2, 1
    

    第三题:
    宏任务嵌套微任务

        console.log(1)
    
        setTimeout(function() {
          console.log(2)
          new Promise(function(resolve) {
            console.log(3)
            resolve()
          }).then(function() {
            console.log(4)
          })
        });
    
        new Promise(function(resolve) {
          console.log(5)
          resolve()
        }).then(function() {
          console.log(6)
        })
    
        setTimeout(function() {
          console.log(7)
          new Promise(function(resolve) {
            console.log(8)
            resolve()
          }).then(function() {
            console.log(9)
          })
        });
    
        // 1 5 6 2 3 4 7 8 9 
    

    第四题:

    Promise.resolve().then(() => {
        console.log(0)
        return Promise.resolve(4)
    }).then((res) => {
        console.log(res)
    })
    
    Promise.resolve().then(() => {
        console.log(1)
    }).then(() => {
        console.log(2)
    }).then(() => {
        console.log(3)
    }).then(() => {
        console.log(5)
    }).then(() => {
        console.log(6)
    })
    
    // 0, 1, 2, 3, 4, 5, 6
    

    相关文章

      网友评论

          本文标题:微任务执行顺序

          本文链接:https://www.haomeiwen.com/subject/omwjertx.html