Promise.resolve和新Promise(resolve)是否可互换

编程入门 行业动态 更新时间:2024-10-28 14:27:18
本文介绍了Promise.resolve和新Promise(resolve)是否可互换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我认为 Promise.resolve 和 new Promise(resolve)是可以互换的.

I think Promise.resolve and new Promise(resolve) are interchangeable.

考虑一下:

A.

new RSVP.Promise(function (resolve, reject) { resolve(); }).then(function () { return new RSVP.Promise(function (resolve) { resolve("HI") }); }).then(function (result) { console.log(result); });

B.

new RSVP.Promise(function (resolve, reject) { resolve(); }).then(function () { return RSVP.resolve("HI"); }).then(function (result) { console.log(result); });

我都期望打印两个"HI".

Both print "HI" as I expected.

所以我认为如果我不需要拒绝"任何东西.为了简单起见,我只能编写 RSVP.resolve(); .

So I think if I don't need to "reject" anything. I can just write RSVP.resolve(); for simplicity.

但请考虑以下示例:

new RSVP.Promise(function (resolve, reject) { resolve(); }).then(function () { return new RSVP.Promise(function (resolve, reject) { setTimeout(function () { resolve("HI") }, 3000); }); }).then(function (result) { console.log(result); });

如何使用 RSVP.resolve(); 进行替换?我尝试了例如:

How can I use RSVP.resolve(); to replace? I tried for example:

new RSVP.Promise(function (resolve, reject) { resolve(); }).then(function () { return setTimeout(function () { return new RSVP.resolve("HI"); }, 3000); }).then(function (result) { console.log(result); });

这将打印其他内容,而不是"HI".因此可以使用RSVP.resolve();这里?这两个可以互换吗?

This prints something else instead of "HI". So is it possible to use RSVP.resolve(); here? Are these two interchangeable?

推荐答案

首要的

我认为Promise.resolve和新的Promise(resolve)是可以互换的.

I think Promise.resolve and new Promise(resolve) are interchangeable.

不. Promise.resolve 将创建一个已解决的承诺,而 new Promise(resolve)将创建一个既未解决也不拒绝的承诺.

Nope. Promise.resolve will create a promise which is already resolved, whereas new Promise(resolve) creates a promise which is neither resolved nor rejected.

在最后一个示例中,

return setTimeout(function () { return new RSVP.resolve("HI"); }, 3000);

表示您要返回的是 setTimeout 函数的结果,而不是诺言对象.因此,当前的 then 处理程序将返回解析的promise,其结果为 setTimeout .这就是为什么您看到一个奇怪的物体.

means that, you are returning the result of setTimeout function, not a promise object. So, the current then handler will return a resolved promise with the result of setTimeout. That is why you are seeing a weird object.

在您的特定情况下,您想在解决承诺之前引入延迟. Promise.resolve 是不可能的.问题中显示的倒数第二种方法是解决方法.

In your particular case, you want to introduce a delay before resolving the promise. It is not possible with Promise.resolve. The penultimate method you have shown in the question, is the way to go.

更多推荐

Promise.resolve和新Promise(resolve)是否可互换

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

发布评论

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

>www.elefans.com

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