返回 Promise 对象的处理结果。如果等待的不是 Promise 对象,则返回该值本身。

如果一个 Promise 被传递给一个 await 操作符,await 将等待 Promise 正常处理完成并返回其处理结果。

function testAwait (x) {  return new Promise(resolve => {    setTimeout(() => {      resolve(x);    }, 2000);  });} async function helloAsync() {  var x = await testAwait ("hello world");  console.log(x); }helloAsync ();// hello world

正常情况下,await 命令后面是一个 Promise 对象,它也可以跟其他值,如字符串,布尔值,数值以及普通函数。

function testAwait(){   console.log("testAwait");}async function helloAsync(){   await testAwait();   console.log("helloAsync");}helloAsync();// testAwait// helloAsync

await针对所跟不同表达式的处理方式:

  • Promise 对象:await 会暂停执行,等待 Promise 对象 resolve,然后恢复 async 函数的执行并返回解析值。

  • 非 Promise 对象:直接返回对应的值。