async await 日常总结

294 阅读1分钟

async 用于申明一个 function 是异步的,而 await 用于等待一个异步方法执行完成,await可以理解为promise的then方法一样,视为微任务;

function test(msg) {
 return new  Promise(resolve => {
     setTimeout(()=>{
         resolve(msg)
     },200)
 })
}
async  function  testAsync(){
  const x  =  await test('你好哇,新朋友!')
    console.log(x)
    console.log('欢迎来到我的世界')
}
testAsync().then()  //你好哇,新朋友!欢迎来到我的世界

ps: 切记promise里面的一定要resolve,否则只执行test方法,后面的两个console.log不执行!