Created
October 30, 2019 05:22
-
-
Save greathmaster/7ddd582112c2a3e69721812d048bcbe7 to your computer and use it in GitHub Desktop.
Example of JS promises, fetch, and asnyc/await
This file contains 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
//Fetch with Promises and explicit functions | |
fetch('https://jsonplaceholder.typicode.com/posts/1') | |
.then(function (res) { return res.json()}) | |
.then(function (data) { | |
//Make use of the data variable here | |
console.log(data) | |
}) | |
//Fetch with Promises and arrow functions | |
fetch('https://jsonplaceholder.typicode.com/posts/2') | |
.then((res) => res.json()) | |
.then((data) => { | |
//Make use of the data variable here | |
console.log(data) | |
}) | |
//Fetch with Async/ Await | |
async function fetchData() { | |
let res = await fetch('https://jsonplaceholder.typicode.com/posts/3') | |
let ret = await res.json() | |
return ret; | |
} | |
//Note that async functions return a Promise so we MUST use .then() | |
//to access the data | |
fetchData().then((data) => { | |
//Make use of the data variable here | |
console.log(data) | |
}) | |
//--------- | |
/*NOTE: The following code will not work as expected:*/ | |
let info = fetchData() | |
console.log(info) | |
/*This is because async functions ALWAYS return a Promise. | |
When we console.log(info) we get a Promise as the output. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment