Simple Promise chain example in modern Javascript (ES6+)
( 27 Articles)

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:
- Calculate Variance and Standard Deviation in Javascript
- Javascript: Capitalize the First Letter of Each Word (Title Case)
- Using Rest Parameters in TypeScript Functions
- Node + TypeScript: Export Default Something based on Conditions
- TypeScript: Function with Optional and Default Parameters
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
0 Comments