为什么在使用异步功能的语句之前执行异步之后的语句?

时间:2018-08-08 08:09:43

标签: javascript ecmascript-6 async-await

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

我不明白我在做什么错?

1 个答案:

答案 0 :(得分:0)

await / async兑现承诺。照原样,getResults同步返回undefined,而它应该返回Promise将会等待的await

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