宏任务-微任务-面试题

面试题一

/*
promise1
2
then1
queueMicrotask1
then3
setTimeout1
then2
then4
setTimeout2
*/
  console.log("script start")//主任务1
  setTimeout(function () {
  console.log("setTimeout1");//宏任务1
  new Promise(function (resolve) {
    resolve();
  }).then(function () {//宏任务1:微任务1
    new Promise(function (resolve) {
      resolve();
    }).then(function () {//宏任务1:微任务2
      console.log("then4");//宏任务1:微任务2:console.log
    });
    console.log("then2");//宏任务1:微任务1:console.log
  });
});

new Promise(function (resolve) {
  console.log("promise1");//主任务2
  resolve();
}).then(function () {
  console.log("then1");//微任务1:console.log
});

setTimeout(function () {
  console.log("setTimeout2");//宏任务2
});

console.log(2);//主任务3

queueMicrotask(() => {
  console.log("queueMicrotask1")//微任务2
});

new Promise(function (resolve) {
  resolve();
}).then(function () {//微任务3
  console.log("then3");
});
console.log("script end")//主任务4

面试题二

    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
posted @ 2024-10-21 20:10  韩德才  阅读(20)  评论(0编辑  收藏  举报