返回課程

非非同步呼叫非非同步

我們有一個稱為 f 的「一般」函式。您如何呼叫 async 函式 wait(),並在 f 內部使用其結果?

async function wait() {
  await new Promise(resolve => setTimeout(resolve, 1000));

  return 10;
}

function f() {
  // ...what should you write here?
  // we need to call async wait() and wait to get 10
  // remember, we can't use "await"
}

附註:這項任務在技術上非常簡單,但對於非同步/等待的新手開發人員來說,這個問題相當常見。

了解其內部運作方式有助於解決此問題。

只要將 async 呼叫視為承諾,並附加 .then 即可

async function wait() {
  await new Promise(resolve => setTimeout(resolve, 1000));

  return 10;
}

function f() {
  // shows 10 after 1 second
  wait().then(result => alert(result));
}

f();