执行上下文:为什么这个javascript代码会这样?
我已经开始学习javascript中的异步编程。 请查看以下代码:执行上下文:为什么这个javascript代码会这样?,javascript,asynchronous,Javascript,Asynchronous,我已经开始学习javascript中的异步编程。 请查看以下代码: constmypromise=()=>Promise.resolve('I have resolve'); 函数firstFunction(){ myPromise().then(res=>console.log(res)); log('firstFunction'); } 异步函数secondFunction(){ log(wait myPromise()); console.log('secondFunction'); }
constmypromise=()=>Promise.resolve('I have resolve');
函数firstFunction(){
myPromise().then(res=>console.log(res));
log('firstFunction');
}
异步函数secondFunction(){
log(wait myPromise());
console.log('secondFunction');
}
第一个函数()
第二个函数()代码>想象以下数字:
1-firstFunction()
2-第二个函数()
3-sayHi()
Hi
排在列表的第二位,因为到达第三位比解决承诺更快。因为1号中的console.log()
不在承诺中,所以它会立即执行,并依次发生在hi
消息之前
1、2和3都会执行,但由于1和2中的承诺值需要x ms才能解析,因此Hi会在任何基于承诺的控制台日志之前打印。为了让消息队列执行存储的消息(来自异步函数),调用堆栈需要为空
您可以在演示此行为的事件循环中查看这一点
在第二种情况下,在执行消息队列中的消息之前,调用堆栈有3个函数需要执行并从中删除,因此必须在异步调用之前打印hi
secondFunction
最后执行,因为它在异步函数中,前面有一个wait。注释:
function firstFunction() {
myPromise().then(res => console.log(res)); // this console.log will be called
//after myPromise() is _resolved_
console.log('firstFunction'); // this console.log will be called
// after function myPromise() is _called_
}
async function secondFunction() {
console.log(await myPromise()); // again, not gonna console.log until myPromise()
// is resolved...
console.log('secondFunction'); // and any subsequent line isn't going to be executed
// until `await` is complete
}
我想你的问题可以简化为->为什么Hi没有显示在最后
。答案是因为在你的代码中没有什么要等待firstFunction
和secondFunction
完成的,就这么简单。“现在调用堆栈是空的”,这就是你错的地方。firstFunction
和secondFunction
都是匿名帧的一部分,需要在事件循环的下一次迭代开始之前完成。这是我缺少的位:firstFunction和secondFunction都是匿名帧的一部分,需要在事件循环的下一次迭代开始之前完成开始感谢伊瓦尔的澄清。