JavaScript Async: Day 15 - Async Callbacks, Promises & Await

𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗦𝗲𝗿𝗶𝗲𝘀 – 𝗗𝗮𝘆 𝟭𝟱: 𝗔𝘀𝘆𝗻𝗰𝗵𝗿𝗼𝗻𝗼𝘂𝘀 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 (𝗖𝗮𝗹𝗹𝗯𝗮𝗰𝗸𝘀, 𝗣𝗿𝗼𝗺𝗶𝘀𝗲𝘀 & 𝗔𝘀𝘆𝗻𝗰/𝗔𝘄𝗮𝗶𝘁) JavaScript is single-threaded, but it can handle asynchronous tasks like API calls, timers, and user interactions without blocking the UI. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗔𝘀𝘆𝗻𝗰𝗵𝗿𝗼𝗻𝗼𝘂𝘀 𝗝𝗦? • Code that runs without waiting • Long tasks run in the background • Keeps the UI responsive 𝗖𝗮𝗹𝗹𝗯𝗮𝗰𝗸 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻 A function passed into another function and executed later. function fetchData(callback) {  setTimeout(() => {   callback("Data loaded");  }, 1000); } fetchData(function (result) {  console.log(result); }); 𝗣𝗿𝗼𝗺𝗶𝘀𝗲𝘀 A promise represents a value that will be available now, later, or never. const promise = new Promise((resolve, reject) => {  resolve("Success"); }); promise.then(result => console.log(result)); 𝗔𝘀𝘆𝗻𝗰 / 𝗔𝘄𝗮𝗶𝘁 Cleaner and more readable way to handle async code. async function getData() {  const result = await promise;  console.log(result); } getData(); 𝗞𝗲𝘆 𝗣𝗼𝗶𝗻𝘁𝘀 • Callbacks were the first async solution • Promises avoid callback hell • async/await makes code readable • Used heavily in API calls 𝗧𝗼𝗱𝗮𝘆’𝘀 𝗣𝗿𝗮𝗰𝘁𝗶𝗰𝗲 • Create a setTimeout example • Convert callback to promise • Use async/await with try–catch • Console log async results Next, we’ll learn 𝗙𝗲𝘁𝗰𝗵 𝗔𝗣𝗜 & 𝗔𝗝𝗔𝗫 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 #JavaScriptSeries #Day15 #AsyncJavaScript #Promises #AsyncAwait #FrontendDevelopment #CodingJourney #techgian

To view or add a comment, sign in

Explore content categories