CI_*_*Guy 5 javascript async-await
所以我试图把我的头放在 promises/await/async 上。我不明白为什么当执行 go() 时,在 console.log(coffee) 之后会出现带有“finished”的警报。当所有函数都使用 await/promises 时,为什么它只等待 getCoffee() 而其他 axios 调用在“完成”警报之后运行?
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();
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>
Run Code Online (Sandbox Code Playgroud)
这里的问题是console.log
并不总是像人们想象的那样同步。该规范仅要求console.log
在开发者控制台中显示一条消息,但没有对如何或何时显示消息做出任何要求。根据您的浏览器,结果可能会有所不同,但通常会实现如下所示的内容:
console.log
请求会被推送到console.log
始终按顺序执行)因为console.log
实际上是这样一个复杂的操作,所以在alert
语句运行之前它可能无法完成执行(在某些浏览器中)。通过将每次调用替换alert
为console.log
或每次调用,console.log
您alert
应该会看到事情实际上是按预期顺序执行的。
归档时间: |
|
查看次数: |
3902 次 |
最近记录: |