Thursday, July 5, 2018

JavaScript Promise Reminder

console.log(`Starting...`);

let success = !true;

const promise = new Promise(function(resolve, reject) {
    setTimeout( () => {
        if (success) 
            resolve("worked");
        else
            reject("failed"); // reject(new Error("failed"));
    }, 1000);
});

console.log(`Async operation in progress...`);

let anotherPromise = promise.then( // then() or catch() return a new promise.
    (result) => {
        console.log(`Then 0 ${result}`);
    }
).catch(
    (err) => {
        console.log(`Catch 0 ${err}`);
    }
);

console.log(`promise === rt: ${promise === anotherPromise}`);

anotherPromise.then(
    (result) => {
        console.log('Then 1');
    }
).catch(
    (err) => {
        console.log(`Catch 1 ${err}`);
    }
);

Result:

With the success variable being false the first promise (promise) fail, but the second one (anotherPromise) succeed.
Pay attention to the fact that the variable promise and anotherPromise are not referencing the same Promise instance.

Starting...
Async operation in progress...
promise === rt: false
Catch 0 failed
Then 1

No comments:

Post a Comment