Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save matt-daniel-brown/ae46f3083bdee51222007414787fce99 to your computer and use it in GitHub Desktop.
Save matt-daniel-brown/ae46f3083bdee51222007414787fce99 to your computer and use it in GitHub Desktop.
Simple ES6 Async Example: Rewriting a promise chain with an async function
/*
* Using An API that returns a Promise will
* result in a promise chain, and it splits
* the function into many parts.
*
* (for example...)
*/
function getProcessedData(url) {
return downloadData(url) // returns a promise
.catch(e => {
return downloadFallbackData(url) // returns a promise
})
.then(v => {
return processDataInWorker(v); // returns a promise
});
}
// ============================================================
/* However, it can be rewritten with a single async function as follows: */
async function getProcessedData(url) {
let v;
try {
v = await downloadData(url);
} catch(e) {
v = await downloadFallbackData(url);
}
return processDataInWorker(v);
}
//--------------------------------------------------------
// Note that in the above example,
// there is no await statement on the return statement,
// because the return value of an async function is
// implicitly wrapped in Promise.resolve.
//--------------------------------------------------------
// Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment