我知道我们都使用promises来避免函数回调地狱,但我的问题是在事件循环中承诺代码运行的位置以及代码是否真的是异步的。
I know we all use promises to avoid function callback hell, but my question is where in the event loop the promise code runs and whether the code is really asynchronous.
我的意思是,这个代码是异步的,因为它是在一个承诺中运行的吗? 或承诺不是事件循环的一部分?
I mean, is this code asynchronous just because it's run within a promise? Or is the promise not a part of the event loop?
const p = new Promise((resolve,reject) =>{ resolve('am i part of the event loop ? , am i a diffrent thread ? or am i synchronized? ') })
推荐答案
承诺如何制作代码异步?
How does promise make code asynchronous?
它没有。
承诺提供了用于处理异步函数的标准接口(例如,使用 .then()方法。)
A promise provides a standard interface (e.g. with a .then() method) for handling asynchronous functions.
如果所有内容都在promise是非异步的,那么代码仍然是非异步的。
If everything done inside a promise is non-asynchronous, then the code is still non-asynchronous.
const p = new Promise((resolve, reject) => { console.log(1); resolve(); console.log(2); }); console.log(3);
您可以在上面看到Promise正在阻塞,就像任何其他非异步代码一样。
You can see, above, that the Promise is blocking just as any other non-asynchronous code is.
更多推荐
promise如何使代码异步?
发布评论