LeC*_*ant 3 asynchronous node.js promise
我对下面的代码有一个奇怪的问题:在函数调用之后添加一个无限循环将阻止在调用内部解决承诺。
我不明白为什么,以及这个循环如何影响承诺行为
const second_call = () => {
return new Promise((resolve, reject) => {
console.log("Second call");
resolve();
});
}
const first_call = () => {
console.log("First call");
second_call().then(() => {
console.log("First call, THEN");
});
}
const main = () => {
console.log("Started");
first_call();
//if if comment the while (true), all debug msgs will be displayed
//if i uncomment the while (true), the msg "First call, THEN" will not be displayed
while (true);
}
main();
Run Code Online (Sandbox Code Playgroud)
你让 EventLoop 忙于无限循环。Node 是单线程的,并使用一组机制来处理并发操作。在这种情况下,您的承诺正在等待 EventLoop 可用于解决承诺结果,但由于您有无限的事情发生,因此永远不会选择和解决承诺。
我建议您阅读有关 EventLoop 在 NodeJS 中的工作原理和并发性的信息。
这里有一些很好的参考:
| 归档时间: |
|
| 查看次数: |
752 次 |
| 最近记录: |