Understanding async keyword in JavaScript functions

Do you know what happens when we add an 𝗮𝘀𝘆𝗻𝗰 keyword to a function? When we add an 𝗮𝘀𝘆𝗻𝗰 keyword to the function, the function always returns a promise fulfilled with the returned value. So the below code: const sayHello = async function () { return 'Hello'; }; is the same as: const sayHello = function () { return new Promise(function (resolve, reject) { resolve('Hello'); }); }; which is the same as: const sayHello = function () { return Promise.resolve('Hello'); }; So to get the actual string 𝗛𝗲𝗹𝗹𝗼, we need to add .𝘁𝗵𝗲𝗻 handler like this: sayHello() .then(function (result) { console.log(result); // Hello }); 𝗣𝗦: 𝗮𝘀𝘆𝗻𝗰 is used along with 𝗮𝘄𝗮𝗶𝘁 keyword to perform some async operation like this: const getData = async function () { try { const {data} = await axios.get('url'); return data; } catch(error) { } }; getData() .then(result => console.log(result)) .catch(error => console.log(error)); 𝗧𝗶𝗽: Always add .𝗰𝗮𝘁𝗰𝗵 handler after .𝘁𝗵𝗲𝗻 to avoid breaking the application If there is some issue while executing the API call. 𝗙𝗼𝗿 𝗺𝗼𝗿𝗲 𝘀𝘂𝗰𝗵 𝘂𝘀𝗲𝗳𝘂𝗹 𝗰𝗼𝗻𝘁𝗲𝗻𝘁, 𝗱𝗼𝗻'𝘁 𝗳𝗼𝗿𝗴𝗲𝘁 𝘁𝗼 𝗳𝗼𝗹𝗹𝗼𝘄 𝗺𝗲. #javascript #reactjs #nextjs #webdevelopment

To view or add a comment, sign in

Explore content categories