Created
May 19, 2018 19:06
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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