Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Promise.resolve and new Promise(resolve) interchangeable

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

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.

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.

So I think if I don't need to "reject" anything. I can just write 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(); 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". So is it possible to use RSVP.resolve(); here? Are these two interchangeable?

like image 804
CSnerd Avatar asked Dec 01 '15 06:12

CSnerd


1 Answers

First and foremost

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

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


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. So, the current then handler will return a resolved promise with the result of 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. The penultimate method you have shown in the question, is the way to go.

like image 188
thefourtheye Avatar answered Sep 20 '22 12:09

thefourtheye