4

I am new to Promise. I wrote two examples:

The first one is:

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

This one will print out "HI" after 3 seconds as I expected. This is because "then" waits on it, and is only called when the promise settles.

The second one is:

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

I thought it will also print "HI" after 3 seconds. But nothing happened. I thought the second "then" will wait on the the promise in the first "then".

what is wrong for the second example and how to fix it?

CSnerd
  • 2,129
  • 8
  • 22
  • 45
  • I've tried it without RSVP, using native promises, and it works on chrome http://codepen.io/anon/pen/MaNxJJ – Carlo Dec 01 '15 at 06:29
  • Yup as thefourtheye has said, you did miss a 'new'. While coping to the codepen I have fixed it without thinking. – Carlo Dec 01 '15 at 06:31

2 Answers2

6

tl;dr

You need to construct RSVP promises with new operator.

Fixed code

new RSVP.Promise(function (resolve, reject) {
    resolve();
}).then(function () {
    // Note the `new` in the next line
    return new RSVP.Promise(function (resolve, reject) {
        setTimeout(function () {
            resolve("HI")
        }, 3000);
    });
}).then(function (result) {
    console.log(result);
}).catch(console.error);

In your case, it was not doing anything because the promise creation in the then handler failed, as new was not used with that. Since, the then handler was throwing an exception, it returned a failed promise. That is why the next then handler also was not executed.

When I executed your original code with the catch handler attached, like I have shown above, I got the following error.

[TypeError: Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.]

Rule of thumb: Always use the catch handler when you are dealing with promises.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
0

In your second example you have a function that returns a promise inside of the then() function, but that promise is not exposed to the proceeding then() so when it resolves there is no action for it to perform. then() actually returns it's own promise, which allows for the chaining to work. In the case of the second example the result in the second then() should be the Promise you returned in the first then()

ecompton3
  • 76
  • 5