TIL Avoiding promise chains
POSTED ON:
TAGS: javascript promises
Callbacks are functions that are executed when another function finishes.
For example:
- Go get data from a website.
- When the data is fetched, then run this 'callback function' to take that data and do something with it.
But now that you understand javascript callbacks you'll soon find yourself in nested "callback hell."
Instead, use a promise!
// simple example of a promise.
// If successful -> resolve argument
// If fail -> reject argument
const myPromise = new Promise(function(resolve, reject) {
setTimeout(function() {
if (Math.random() < 0.9) {
return resolve('Hooray!');
}
return reject('Oh no!');
}, 1000);
});
// If successful, move to then()
// if fail, then move to catch()
myPromise
.then(function(data) {
console.log('Success: ' + data);
})
.catch(function(err) {
console.log('Error: ' + err);
});
But the main thing I wanted to point out is avoiding promise chains!
// The wrong way
getSomeData.then(data => {
getSomeMoreData(data).then(newData => {
getSomeRelatedData(newData => {
console.log(newData);
});
});
});
// The right way
// version 1
getSomeData
.then(data => {
return getSomeMoreData(data);
})
.then(data => {
return getSomeRelatedData(data);
})
.then(data => {
console.log(data);
});
// version 2 - ES6
getSomeData
.then(data => getSomeMoreData(data))
.then(data => getSomeRelatedData(data))
.then(data => console.log(data));
// version 3 - the shortest way
getSomeData
.then(getSomeMoreData)
.then(getSomeRelatedData)
.then(console.log);
Version 3 works because, in layman terms, successful data moves to the next then
statement.
via A Collection of JavaScript Tips Based on Common Areas of Confusion or Misunderstanding
Related TILs
Tagged: javascript