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
我不明白我在做什么错?
答案 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。