简体   繁体   English

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

[英]Are Promise.resolve and new Promise(resolve) interchangeable

I think Promise.resolve and new Promise(resolve) are interchangeable. 我认为Promise.resolvenew Promise(resolve)是可以互换的。

Consider this: 考虑一下:

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. B.

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

Both print "HI" as I expected. 两者都按照我的预期打印“HI”。

So I think if I don't need to "reject" anything. 所以我想如果我不需要“拒绝”任何东西。 I can just write RSVP.resolve(); 我可以写RSVP.resolve(); for simplicity. 为简单起见。

But consider this example: 但请考虑这个例子:

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);
});

How can I use RSVP.resolve(); 我怎样才能使用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);
});

This prints something else instead of "HI". 这打印出别的东西而不是“HI”。 So is it possible to use RSVP.resolve(); 那么可以使用RSVP.resolve(); here? 这里? Are these two interchangeable? 这两个可以互换吗?

First and foremost 首先是最重要的

I think Promise.resolve and new Promise(resolve) are interchangeable. 我认为Promise.resolve和新的Promise(解决)是可以互换的。

Nope. 不。 Promise.resolve will create a promise which is already resolved, whereas new Promise(resolve) creates a promise which is neither resolved nor rejected. Promise.resolve将创建一个已经解决的承诺,而new Promise(resolve)创建一个既未解决也Promise.resolve拒绝的承诺。


In the last example, 在最后一个例子中,

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

means that, you are returning the result of setTimeout function, not a promise object. 意味着,您将返回setTimeout函数的结果,而不是promise对象。 So, the current then handler will return a resolved promise with the result of setTimeout . 因此,目前的then处理程序将返回结果的解决承诺setTimeout That is why you are seeing a weird object. 这就是为什么你看到一个奇怪的对象。


In your particular case, you want to introduce a delay before resolving the promise. 在您的特定情况下,您希望在解决承诺之前引入延迟。 It is not possible with Promise.resolve . Promise.resolve是不可能的。 The penultimate method you have shown in the question, is the way to go. 您在问题中显示的倒数第二种方法是要走的路。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM