Skip to content

Instantly share code, notes, and snippets.

@ravikp7
Created May 14, 2019 15:16
Show Gist options
  • Save ravikp7/224359418491dc911198f585d9b41339 to your computer and use it in GitHub Desktop.
Save ravikp7/224359418491dc911198f585d9b41339 to your computer and use it in GitHub Desktop.
Comparing different async JS styles
// A library
const getImage = (url, callback) => {};
const imageUrls = [];
// Callback
/**
* This callback style code is least readable.
* It has trust issue as we depend upon getImage library to execute our callback.
* There may be a bug in the library and it may never run the callback
*/
imageUrls.forEach(url => {
getImage(url, (error, data) => {
if (error) {
console.error(error);
} else {
// Do something with data
}
});
});
/**
* Let's promisify the library with a timeout
* @returns Promise
* Rejects in 2s if the request is not completed
*/
const getImagePromise = url =>
new Promise((resolve, reject) => {
const timeout = 2000;
setTimeout(() => reject(new Error('Timeout!!')), timeout);
getImage(url, (error, data) => {
if (error) {
reject(new Error('Timeout!!'));
} else {
resolve(data);
}
});
});
/**
* The benefit of using this is that now we've more control
* With promise style, we've lesser nested callbacks, it's more readable
* It'd be more evident if we had more callbacks
*/
// Promise
imageUrls.forEach(url => {
getImagePromise(url)
.then(data => {
// Do something with data
})
.catch(error => {
console.error(error);
});
});
/**
* Finally we've the best readability with async/await
* It'd be more evident with more promises
*/
// Async await
imageUrls.forEach(async url => {
try {
const data = await getImagePromise(url);
// Do something with data
} catch (error) {
console.error(error);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment