async&await 与事件循环

133 阅读1分钟

async&await 与事件循环

  • 1、async 返回的是一个 Promise 对象
  • 2、await 的结果,取决后面函数的返回值
  • 3、await 下面的语句相当于 Promise.resolve().then(()=>{执行语句})
/*
 script start
 async start
 async2
 promise1
 script end
 async1 end
 promise2
 async3 end
 setTimeout
*/ 

async function async1() {
  console.log('async start')
  await async2()
  console.log('async1 end')
  await 3
  console.log('async3 end')
}
async function async2() {
  console.log('async2')
  return 'async2'
}
console.log('script start')
setTimeout(()=>{
  console.log('setTimeout')
})
async1()

new Promise(function(resolve){
  console.log('promise1')
  resolve()
}).then(function(){
  console.log('promise2')
})
console.log('script end')

async-await.png