Vaguely when a promise from setTimeout

I am new to Promise. I wrote two examples:

The first:

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

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

Second:

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 he would also print “HI” in 3 seconds. But nothing happened. I thought that the second “then” would wait for the promise in the first “then”.

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

+4
source share
2 answers

TL; DR

You need to build RSVP promises with an operator new.

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

, then , new . then , . then .

catch, , .

[TypeError: "Promise": "" , .]

. catch, promises.

+6

, then(), then(), , , . () , . () , , ()

0

Source: https://habr.com/ru/post/1618069/


All Articles