【问题标题】:why is statement after async is executed before statement with async function?为什么 async 之后的语句在带有 async 函数的语句之前执行?
【发布时间】:2018-08-08 08:09:42
【问题描述】:
function renderLoader() {
    console.log("Loading");
}

function getResults() {
    setTimeout(myTimeout, 3000)
}  

function myTimeout() {
    console.log("The Results");
}

function clearLoader() {
   console.log("Loading over");
}

const controlSearch = async () => {
    renderLoader();
    await getResults();
    clearLoader();
}

controlSearch();

我是异步/等待的新手。我预计上述代码的结果是

Loading  //then wait for 3 seconds
Results
Loading over

但它却产生了这个,

Loading
Loading over //then wait for 3 secs
Results

我不明白我做错了什么?

【问题讨论】:

  • getResults 不返回 Promise

标签: javascript ecmascript-6 async-await


【解决方案1】:

await/async 玩承诺。照原样,getResults 同步返回 undefined,而它应该返回 Promiseawait 将,嗯,等待:

function getResults() {
  return new Promise((resolve) => {
    setTimeout(() => {
      myTimeout();
      resolve();
    }, 3000)
  });
}

或者:

function getResults() {
  return new Promise((resolve) => {
    setTimeout(resolve, 3000)
  }).then(myTimeout);
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await

【讨论】:

  • 我已阅读文档。我的理解是,即使我没有明确提及返回,也会返回一个承诺。现在,我知道它是“未定义的”。
猜你喜欢
  • 2022-01-07
  • 1970-01-01
  • 2016-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多