promise如何使代码异步?

编程入门 行业动态 更新时间:2024-10-18 21:24:28
本文介绍了promise如何使代码异步?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我知道我们都使用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如何使代码异步?

本文发布于:2023-11-13 00:34:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1582920.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:代码   promise

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!