Simple Promise chain example in modern Javascript (ES6+)

Last updated on February 13, 2022 A Goodman Loading... Post a comment

The simple and easy-to-understand example below shows you how to use the Promise chain in modern Javascript (ES6, ES7, ES8, or newer).

The code:

let x = 1; // or whatever you like
const p = new Promise((resolve, reject) => {
    setTimeout(() => {
        if (typeof x == 'number') {
            resolve(x + 1);
        } else {
            reject('X is not a number!');
        }
    })
});

p.then((x) => {
        console.log('x', x);
        return x + 1;
    })
    .then(y => {
        console.log('y', y);
        return y + 1;
    })
    .then(z => {
        console.log('z', z);
        return z + 1;
    })
    .then(w => {
        console.log('w', w);
        return w + 1;
    })
    .then(t => {
        console.log('t', t);
        return t + 1;
    })
    .finally(() => {
        console.log('Finally', 'finished');
    })
    .catch(err => {
        console.log(err);
    })

Output:

x 2
y 3
z 4
w 5
t 6
Finally finished

Further reading:

I have made every effort to ensure that every piece of code in this article works properly, but I may have made some mistakes or omissions. If so, please send me an email: [email protected] or leave a comment to report errors.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles