Skip to content

宏任务:

定时器,ajax,读取文件

微任务:

promise.then

(只有 then 是异步的,放在 new Promise()里的代码是同步的)

async 是 new promise 的简写

js
//以下两个函数式一样的

async function fn() {
  return 1
}

function fn() {
  return new Promise((resolve) => {
    resolve(1)
  })
}

await 关键字

js
async function fun1() {
  let data = await fun2()
  console.log(data)
}

async function fun2() {
  console.log(200)
  return 100
}

fun1()
//输入结果:200,100

综合题:

js
console.log(1)
async function async1(){
    await async2()
    console.log(2)
}
async function async2(){
    console.log(3)
    //没有return值,等于没有reslove
}
async1()
setTimeout(function(){
    console.log(4)
},0)
new Promise(resolve=>{
    console.log(5)
    resolve()
}).then(function(){
    console.log(6)
}).then(function()=>{
    console.log(7)
})
console.log(8)

// 先看同步,再找process.nextTick,再找微任务,然后宏任务,最后setImmediate
// 遇到函数就执行函数,看到await就跳过,但是await的函数会被执行,只是结果会被阻塞(加入微任务队列中)
//输出顺序:1,3,5,8,2,6,7,4

Last updated: