// In JavaScript, An async function is a function declared with the async keyword, and the await keyword can then be permitted within it.// Example;functionresolveAfter2Seconds(){returnnewPromise(resolve=>{setTimeout(()=>{resolve('resolved');},2000);});}asyncfunctionasyncCall(){console.log('calling');const result =awaitresolveAfter2Seconds();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;asyncfunctionresolveAfter2Seconds(){returnnewPromise(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 promiseconstuser=()=>{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/awaitconstuser=async()=>{// you must have use async keyword before use awaitconst data =awaitfetch("https://randomuser.me/api/?results=1");console.log(data);// if error occured it will be null or empty}
constyourAsyncFunction=async()=>{// do something asynchronously and return a promisereturn result;}
anArray.forEach(asyncitem=>{// do something asynchronously for each item in 'anArray'// one could also use .map here to return an array of promises to use with 'Promise.all()'});
server.getPeople().then(asyncpeople=>{
people.forEach(person=>{// do something asynchronously for each person});});
//ORIGINAL//each .then() returns a promisse and can be chained. The .then() will run after the previous one has finished. It emulates an async/await behavior.fetch('https://jsonplaceholder.typicode.com/users')//fetch the content.then((response)=> response.json())//then use that content and convert it to a javascript object.then(users=>{const firstUser = users[0];console.log(firstUser);returnfetch('https://jsonplaceholder.typicode.com/posts?userId='+ firstUser.id);})//then return the content from posts related to that user ID.then((response)=> response.json())//then use that content and convert it to a javascript object.then(posts=>console.log(posts));//then log the result//ASYNC/AWAITconstmyAsyncFunction=async()=>{//define that this will be asynchronousconst usersResponse =awaitfetch('https://jsonplaceholder.typicode.com/users');//wait for the fecth result and put it in the variableconst users =await usersResponse.json();//wait for the previous item to be done, transform it into a javascript object and put it in the variableconst secondUser = users[1];console.log(secondUser);//then log the resultconst postsResponse =awaitfetch('https://jsonplaceholder.typicode.com/posts?userId='+ secondUser.id);//wait for the previous item to be done, wait for the fecth result and put it in the variableconst posts =await postsResponse.json();//wait for the previous item to be done, transform it into a javascript object and put it in the variableconsole.log(posts);//then log the result}myAsyncFunction();
// Old School Javascript Invoke(asyncfunction(){awaitsomeAsyncFunction();})();//New ES6 Javascript Invoke(async()=>{awaitsomeAsyncFunction();})();//Example (async & await)functiondelayResult(){returnnewPromise(resolve=>{setTimeout(()=>{resolve(‘Done’);},5000)})}asyncfunctiongetResult(){let result =awaitdelayResult();return result;}getResult();//New Example constdata=async()=>{const got =awaitfetch('https://jsonplaceholder.typicode.com/todos/1');console.log(await got.json())}data();
//used in node.jsconst fetch =require('node-fetch');asyncfunctionShowuser(){const result =awaitfetch('https://jsonplaceholder.typicode.com/todos/1');const date =await result.json();console.log(date);}Showuser();
// 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)asyncfunctionRandomImage(){//remember async and await is powerful for async operations, always await should be inside of async only.try{const raw_response =awaitfetch("https://www.themealdb.com/api/json/v1/1/random.php");if(!raw_response.ok){// check for the 404 errorsthrownewError(raw_response.status);}const json_data =await raw_response.json();//AWAITlet data = json_data.meals[0];console.log(data);}catch(error){// catch block for network errorsconsole.log(error);}}RandomImage();//(Example 2 : returning another promise)console.log("1 is working");console.log("2 is working");varAsyncFunction=async()=>{var x =newPromise((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");
functiondelayResult(){returnnewPromise(resolve=>{setTimeout(()=>{resolve(‘Done’);},5000)})}asyncfunctiongetResult(){let result =awaitdelayResult();return result;}getResult();
asyncfunctionf(){try{let response =awaitfetch('/no-user-here');let user =await response.json();}catch(err){// catches errors both in fetch and response.jsonalert(err);}}f();
//Async function (JAVASCRIPT)//async function have 1 main purpose://Being able to use 'await' in a functionfunctionexample(){returnawaitfetch('https://mysite.com/api');//error}asyncfunctionsmartexample(){returnawaitfetch('https://mysite.com/api');//mhmm!}
// example of async and await in javascript// First create promiseletmyPromise=()=>{returnnewPromise((resolve, reject)=>{setTimeout(()=>{resolve('Yay, I resolved!')},1000);});}// async without await keywordasyncfunctionnoAwait(){let value =myPromise();console.log(value);}// async with await keywordasyncfunctionyesAwait(){let value =awaitmyPromise();console.log(value);}noAwait();// Prints: Promise { <pending> }yesAwait();// Prints: Yay, I resolved!
we can only use await keyword before a function that
returns either a promise or is itself async.Note: we can use asyncfunction or function returning
a Promisewith.then()
fetch('coffee.jpg').then(response=>{if(!response.ok){thrownewError(`HTTP error! status: ${response.status}`);}else{return response.blob();}}).then(myBlob=>{let objectURL =URL.createObjectURL(myBlob);let image =document.createElement('img');
image.src= objectURL;document.body.appendChild(image);}).catch(e=>{console.log('There has been a problem with your fetch operation: '+ e.message);});