Using promises instead of callback functions
Before promises come to JavaScript we had to rely on callback functions when we needed something to be done after an async action. Let's say we have functions first() and second() and we want them to run in sequence, however first() has some async actions happening inside it. This is how we used to run them before promises:
function first(callback) {
console.log("first starting...");
setTimeout(() => {
// do some stuff here...
callback();
}, 500);
}
function second() {
console.log("second starting...");
}
first(second);
Now with promises we can run these functions in sequence without using a callback:
function first() {
console.log("first starting...");
return new Promise((resolve, reject) => {
setTimeout(() => {
// do some stuff here...
resolve();
}, 500);
});
}
function second() {
console.log("second starting...");
}
first().then(second);
In other words, promises allow us to chain functions using their .then() method which is a cleaner syntax than using callback functions, specially when more functions need to run after one another.