Today I Learned - Rocky Kev

TIL Avoiding promise chains

POSTED ON:

TAGS:

Callbacks are functions that are executed when another function finishes.

For example:

  1. Go get data from a website.
  2. 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!

MDN 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:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL how to hide your JS code

ONE THING TO NOTE: Encrypting a script is stronger than obfuscation, both methods are still not adequate to protect secret content. Honestly, I don't think it's worth it on a production site, and instead just go with pure server-side if you want security. But it's fascinating.