Promise.resolve和新Promise(resolve)是否可互换 [英] Are Promise.resolve and new Promise(resolve) interchangeable
问题描述
我认为 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)是否可互换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!