Created
November 22, 2017 17:11
-
-
Save ConnerAiken/9a0358f5e3bef750162f00defb16df99 to your computer and use it in GitHub Desktop.
Async/Await example
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<script> | |
const validUrl = 'https://jsonplaceholder.typicode.com/posts'; | |
const invalidUrl = 'https://jsonplaceholder.invalid.domain.com/posts'; | |
function downloadData(url) { | |
console.log(`[downloadData()] attempting AJAX request to ${url}`); | |
return $.ajax({ | |
url: url, | |
type: 'GET' | |
}); | |
} | |
function showCachedData() { | |
return { | |
status: 'error', | |
data: {'some': 'data'} | |
}; | |
} | |
/* ====================== | |
ES6 Promise Version | |
==================== | |
function getProcessedData() { | |
return downloadData() | |
.catch(e => { | |
return {error: true, msg: e}; | |
}) | |
.then(v => { | |
return v; | |
}); | |
} | |
*/ | |
/* ====================== | |
New Async/Await Version | |
==================== */ | |
async function getProcessedData(url) { | |
let v; | |
try { | |
v = await downloadData(url); | |
} catch(e) { | |
v = showCachedData(url); | |
} | |
console.log(v); | |
return v; | |
} | |
</script> | |
<title></title> | |
</head> | |
<body> | |
<h2>Output in console.</h2> | |
<button onclick="getProcessedData(validUrl)">Trigger Ajax Success</button> | |
<button onclick="getProcessedData(invalidUrl)">Trigger Ajax Failure</button> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment