Promise vs setTimeout [英] Promise vs setTimeout

查看:145
本文介绍了Promise vs setTimeout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在以下代码中观察到:

I've observed that in the following code:

setTimeout(function(){console.log('setTimeout')});
Promise.resolve(1).then(function(){console.log('promise resolve')})

无论我执行多少次,promise回调总是在setTimeout之前记录。

No matter how many times I execute this, the promise callback always logs before the setTimeout.

我的理解是两个回调都被安排在执行到下一个滴答,我真的不明白发生了什么使得承诺总是优先于超时。

My understanding is that both callbacks are scheduled to be executed to the next tick, and I don't really understand what is going on that makes the promise always take precendence over the timeout.

推荐答案

简短答案Promise比事件循环堆栈中的setTimeout回调函数(或我如何理解)具有更好的优先级。

Short answer Promises have better priority than setTimeout callback function in event loop stack(or how i understand it).

长答案观看此视频。很有帮助。希望这会有所帮助。

Long answer watch this video. Very helpful. Hope this helps.

https:// www.youtube.com/watch?v=8aGhZQkoFbQ

感谢@MickJuice提供有关事件循环的新视频和更新视频。

Thanks @MickJuice for new and updated video for event loop.

https://www.youtube.com/watch?v=cCOL7MC4Pl0

这篇关于Promise vs setTimeout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆