Simple Promise chain example in modern Javascript (ES6+)

February 9, 2020 Goodman Loading... Post a comment

A simple and easy to understand example of how to use Promise chain in modern Javascript (ES6, ES7, ES8 or higher).

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
avatar

Related Articles