async awiat
const data = async () => {
const got = await fetch('https://jsonplaceholder.typicode.com/todos/1');
console.log(await got.json())
}
data();
async awiat
const data = async () => {
const got = await fetch('https://jsonplaceholder.typicode.com/todos/1');
console.log(await got.json())
}
data();
how to make an async function
function resolveAfter2Seconds() {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved');
}, 2000);
});
}
//async function:
async function asyncCall() {
console.log('calling');
const result = await resolveAfter2Seconds();
console.log(result);
// expected output: 'resolved'
}
asyncCall();
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');
}
}
async
function resolveAfter2Seconds() {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved');
}, 2000);
});
}
async function asyncCall() {
console.log('calling');
const result = await resolveAfter2Seconds();
console.log(result);
// expected output: 'resolved'
}
asyncCall();
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;
}
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us