所以我试图理解Promise/await/async。我不明白为什么当执行go()时,带有“完成”警报的部分会紧接着console.log(coffee)输出。为什么只等待getCoffee(),而其他axios调用在所有函数都使用await/promise时才会在“完成”警报之后运行?
function getCoffee() {
return new Promise(resolve => {
setTimeout(() => resolve("☕"), 2000); // it takes 2 seconds to make coffee
});
}
async function go() {
try {
alert("ok");
const coffee = await getCoffee();
console.log(coffee); // ☕
const wes = await axios("https://randomuser.me/api/?results=200");
console.log("wes"); // using string instead of value for brevity
const wordPromise = axios("https://randomuser.me/api/?results=200");
console.log("wordPromise"); // using string instead of value for brevity
alert("finish");
} catch (e) {
console.error(e); //
}
}
go();
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>
alert("finish")
正确运行,但你没有及时在控制台中看到wes
。向控制台记录不总是即时操作(无论您记录什么都必须进行处理、布局和绘制)。本质上,console.log
可以被认为是一个保证按顺序运行的异步操作。尝试将console.log
替换为alert
或将alert
替换为console.log
,看看是否正确。 - stevendesufinish
被警报时控制台日志也可见。 - Patrick Roberts