await async

74 阅读1分钟

如果async函数返回的是一个promise对象,则会以返回的promise为准;若返回的不是promise对象,会自动将返回值用promise.resolve()包装一下.

async function testaSync(){
     return 123;
}
输出: Promise {<resolved>: 123}

await只能用在async函数内部,用在外边会报错.await代表的是在等后面表达式的值(从右向左执行);对于等待的结果可能有两种情况:

  1. 不是promise对象那 await 表达式的运算结果就是它等到的东西.
  2. 是promise对象, await 就忙起来了,它会阻塞后面的代码,等着 Promise 对象 resolve,然后得到 resolve 的值,作为 await 表达式的运算结果。
console.log('script start')

async function async1() {
  await async2()
  console.log('async1 end')
}

async function async2() {
  console.log('async2 end')
}
async1()

setTimeout(function() {
  console.log('setTimeout')
}, 0)

new Promise(resolve => {
  console.log('Promise')
  resolve()
})
  .then(function() {
    console.log('promise1')
  })
  .then(function() {
    console.log('promise2')
  })

console.log('script end')

输出:
script start
async2 end
Promise
script end
async1 end
promise1
promise2
setTimeout

执行完await后面的函数后会暂时跳出async函数去执行外面的同步代码,等同步代码执行完了,会再次回到async函数,将await的值作为表达式的结果,等await中的promise状态为fulfilled,然后把resolve的参数作为await表达式的结果.