// In JavaScript, An async function is a function declared with the async keyword, and the await keyword can then be permitted within it.
// Example;
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();
// The asnycCall function when run will wait for the await block which calls resolveAfter2Seconds() before it logs the output to the console.
// We can also use the then method to wait for an async call before running another block of code.
// Example;
async function resolveAfter2Seconds() {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved');
}, 2000);
});
}
resolveAfter2Seconds().then(
function(result){console.log(result)}
function(error){console.log(result)}
);
// There are so many other ways of writing asychronous functions in javascript.
// Javascript is itself an asychronous language.
// example using promise
const user = () => {
fetch("https://randomuser.me/api/?results=1")
.then((data) => {
console.log(data); // here you recive data
}).catch((err)=>{
console.log(err); // here error
});
}
// example using async/await
const user = async () => {
// you must have use async keyword before use await
const data = await fetch("https://randomuser.me/api/?results=1");
console.log(data); // if error occured it will be null or empty
}
// 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");
async function f() {
try {
let response = await fetch('/no-user-here');
let user = await response.json();
} catch(err) {
// catches errors both in fetch and response.json
alert(err);
}
}
f();
// example of promise and async in javascript
// 1) promise: we need to write new keyword to create promise
function withConstructor(num){
return new Promise((resolve, reject) => {
if (num === 0){
resolve('zero');
} else {
resolve('not zero');
}
});
}
withConstructor(0)
.then((resolveValue) => {
console.log(` withConstructor(0) returned a promise which resolved to: ${resolveValue}.`);
});
// Output: withConstructor(0) returned a promise which resolved to: zero.
// 2) async: we don't need to write new keyword to create promise
async function withAsync(num){
if (num === 0) {
return 'zero';
} else {
return 'not zero';
}
}
withAsync(100)
.then((resolveValue) => {
console.log(` withAsync(100) returned a promise which resolved to: ${resolveValue}.`);
})
// Output: withAsync(100) returned a promise which resolved to: not zero.
we can only use await keyword before a function that
returns either a promise or is itself async.
Note: we can use async function or function returning
a Promise with .then()