Promise 与 setTimeout [英] Promise vs setTimeout

查看:48
本文介绍了Promise 与 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.

推荐答案

Short answer Promises 在事件循环堆栈中比 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 与 setTimeout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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