您什么时候要创建自己的JavaScript承诺?

发布于 2025-01-28 05:55:06 字数 379 浏览 3 评论 0原文

我是JavaScript的新手,并了解了承诺。我在弄清楚何时想创造自己的诺言时遇到了一些麻烦。最初,我的印象是,浏览器API(如果您的JavaScript在浏览器中运行)对“执行器函数”(您传递到Promise构造函数)的处理。有了这种理解,例如,您可以使用创建的承诺在后台进行一些长期运行的计算。

但是,我了解到,一旦创建承诺,执行程序函数实际上是同步执行的(如果您在该执行程序函数中有一些长期运行的代码,则会阻止执行的主线程)。因此,现在我想知道在什么情况下您想定义自己的诺言。我的理解是,例如Fetch等许多异步功能已经返回承诺 - 因此,将这些功能包裹在承诺中是多余的。

有人可以给我一个例子,说明您何时想创造自己的诺言?抱歉,如果这是一个愚蠢的问题,或者我的理解不足,仍然在学习。

提前致谢!

I am new to JavaScript and learning about Promises. I am having some trouble figuring out when you would want to create your own Promise. Initially I was under the impression that the "executor function" (the function you pass into the Promise constructor) was handled asynchronously by the browser API (if your JavaScript is running in a browser). With that understanding you could then, for example, use your created Promise to perform some long-running calculation asynchronously in the background.

However, I learned that the executor function is actually executed synchronously as soon as the Promise is created (thus blocking the main thread of execution if you have a some long running code in that executor function). So now I'm wondering in what cases would you want to define your own Promises. My understanding is that a lot of the asynchronous functions like fetch for example already return promises - and thus it would be redundant to wrap those functions in a promise.

Can someone give me an example of when you would want to create your own Promise? Sorry if this is a silly question or if my understanding is off, still learning.

Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

谈情不如逗狗 2025-02-04 05:55:06

我的理解是,例如fetch的许多异步功能已经返回Promises

实际上已经返回承诺,大多数人都没有。 settimeoutaddeventListener等 - 它们都需要回调,需要 当您想使用诺言时。

已经返回承诺的本机功能的趋势仍然是最近发生的,只有fetch这样的新API。对于图书馆,图片相似 - 现代图书馆将提供承诺,但旧图书馆仍然存在。

除此之外,您是对的 - 您很少需要新的Promise,在正常代码中,您要做的就是保证链接(甚至只是使用async/等待)。但是,新的Promise仍然是所有这些抽象基础的原始构建块,并且不会消失。

My understanding is that a lot of the asynchronous functions like fetch for example already return promises

Actually, most don't. setTimeout, addEventListener, etc - they all take a callback and need to be promisified when you want to use a promise.

The trend to native functions that already return promises is still a recent occurrence, only new APIs like fetch do this. For libraries, the picture is similar - modern libraries will provide promises, but old ones are still around.

Apart from that, you're right - you rarely need new Promise, in normal code all you'll do is promise chaining (or even just use async/await). However, new Promise is still the primitive building block that underlies all these abstractions, and it won't go away.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文