await 到底在等待什么

39 阅读1分钟

await 在等什么?—— 两种情况

等待一个 非 Promise 值(同步值)

function getSomething() {
  return "something";
}

async function test() {
  const v1 = await getSomething(); // 等待 "something"
  console.log(v1); // 立即输出: something
}

test();

await 遇到非 Promise 值时,不会真正“等待” ,而是立即返回该值。

等待一个 Promise 对象

function testAsy(x) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(x);
    }, 3000);
  });
}

async function testAwt() {
  let result = await testAsy('hello world'); // 等待 Promise resolve
  console.log(result);    // 3秒后输出: hello world
  console.log('cuger');   // 3秒后输出: cuger
}

testAwt();
console.log('cug'); // 立即输出: cug

:只有当 await 右侧是 Promise 时,等待 promise 状态的改变,后的值

``

async function fetchData() {
   let response = await fetch('https://api.example.com/data');
   //
   let data = await response.json();
   console.log(data);
}
fetchData();

fetch 成功值是一个异步对象,所以还得awiat