async await and then code example
Example 1: async await
const data = async () => {
const got = await fetch('https://jsonplaceholder.typicode.com/todos/1');
console.log(await got.json())
}
data();
Example 2: js async await
/* Notes:
1. written like synchronous code
2. compatible with try/catch blocks
3. avoids chaining .then statements
4. async functions always return a promise
5. function pauses on each await expression
6. A non promise value is converted to
Promise.resolve(value) and then resolved
*/
// Syntax
// Function Declaration
async function myFunction(){
await ... // some code goes here
}
// Arrow Declaration
const myFunction2 = async () => {
await ... // some code goes here
}
// OBJECT METHODS
const obj = {
async getName() {
return fetch('https://www.example.com');
}
}
// IN A CLASS
class Obj {
// getters and setter CANNOT be async
async getResource {
return fetch('https://www.example.com');
}
}
Example 3: javscript async await explained
// Promise approach
function getJSON(){
// To make the function blocking we manually create a Promise.
return new Promise( function(resolve) {
axios.get('https://tutorialzine.com/misc/files/example.json')
.then( function(json) {
// The data from the request is available in a .then block
// We return the result using resolve.
resolve(json);
});
});
}
// Async/Await approach
// The async keyword will automatically create a new Promise and return it.
async function getJSONAsync(){
// The await keyword saves us from having to write a .then() block.
let json = await axios.get('https://tutorialzine.com/misc/files/example.json');
// The result of the GET request is available in the json variable.
// We return it just like in a regular synchronous function.
return json;
}
Example 4: async await
// ASYNC will always returns promises
// NOTE : AWAIT should be kept only inside ASYNC function
// AWAIT can't be used in regular function
/* TIPS : Js is single threaded & synchronous in nature BUT, we can
make it as asyncronous by using (ASYNC/AWAIT)*/
//(Example 1 : fetching Random Image)
async function RandomImage(){ //remember async and await is powerful for async operations, always await should be inside of async only.
try {
const raw_response = await fetch("https://www.themealdb.com/api/json/v1/1/random.php");
if (!raw_response.ok) { // check for the 404 errors
throw new Error(raw_response.status);
}
const json_data = await raw_response.json(); //AWAIT
let data = json_data.meals[0];
console.log(data);
}
catch (error) { // catch block for network errors
console.log(error);
}
}
RandomImage();
//(Example 2 : returning another promise)
console.log("1 is working");
console.log("2 is working");
var AsyncFunction = async() => {
var x = new Promise((resolve,reject) => {
setTimeout(() => resolve("3 is working"), 3000);
});
var result = await x;
return result;
}
AsyncFunction().then(resolved => console.log(resolved));
console.log("3 is working");