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
Understanding async keyword in JavaScript functions
More Relevant Posts
-
Ever struggled with unexpected req.body values or mismatched types in your Node.js API? Parsing requests isn’t just calling JSON.parse() - it’s handling raw bytes, headers, content-types and boundaries correctly. This guide from Webdock breaks it down: • How Node.js handles different body formats (application/json, x-www-form-urlencoded, multipart/form-data) • What happens under the hood when the data arrives, how streams, buffers and encoding play a role • Practical code examples showing correct parsing and common pitfalls 📘 Read it here: https://lnkd.in/eQQ9msym #Webdock #NodeJS #JavaScript #API #Sysadmins #CloudHosting #NoFluff
To view or add a comment, sign in
-
-
🧩 Top-Level Await - Async Code Made Simple! ⚡ JavaScript just got smarter - you can now use await directly at the top level of your modules without wrapping it inside an async function! 😎 💡 What it means: No more writing this 👇 (async () => { const data = await fetchData(); console.log(data); })(); Now you can simply do 👇 const data = await fetchData(); console.log(data); ✅ Why it’s awesome: • Cleaner async code at the module level • Great for initializing data before rendering apps • Works perfectly with ES modules (ESM) • Makes async setup logic feel synchronous ⚙️ Use Case Example: Fetching config, environment data, or translations before your app starts 🌍 JavaScript keeps getting better - less boilerplate, more clarity! 💪 #JavaScript #AsyncProgramming #WebDevelopment #ReactJS #ReactNative #ESModules #CodingTips #FrontendDevelopment #TypeScript #Developer
To view or add a comment, sign in
-
⚛️ React 19 – New & Updated Hooks use() → Lets you directly use async data or promises inside components without useEffect, simplifying data fetching. 🧠 Example: const user = use(fetchUser()); useOptimistic() → Makes optimistic UI updates easy by letting you show temporary data before the server confirms changes. 🧠 Example: Instantly add a todo to the list before it’s saved. useActionState() → Manages form state, submission, and errors in one place, making form handling cleaner. 🧠 Example: Handle loading and validation directly with one hook. useFormStatus() → Gives real-time status of a form (like pending or submitted) during server actions. 🧠 Example: Disable the submit button while the form is sending data. useDeferredValue() (from React 18) → Defers rendering of slow components to keep the UI responsive. 🧠 Example: Smooth typing experience during heavy data filtering. useTransition() (from React 18) → Allows marking state updates as non-urgent, improving perceived performance. 🧠 Example: Show loading spinner while background updates happen. React 18 improved performance with concurrent rendering and transitions, React 19 makes async data and forms simpler and more intuitive with use(), useOptimistic(), and useActionState(). #react #reactjs #nextjs #javascript #frontend
To view or add a comment, sign in
-
JavaScript Feature: Fetch API The Fetch API is a modern way to make HTTP requests in JavaScript. It’s promise-based, making it cleaner and easier than the old XMLHttpRequest. Basic Usage: fetch('https://lnkd.in/gWKpgMrT') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); fetch() returns a Promise. response.json() parses the response into JSON. .catch() handles errors gracefully. Using Async/Await for Cleaner Syntax: async function getData() { try { const response = await fetch('https://lnkd.in/gWKpgMrT'); const data = await response.json(); console.log(data); } catch (error) { console.error('Error:', error); } } getData(); Pro Tips: Always handle network errors. Use headers for authentication or content-type. Can be used for GET, POST, PUT, DELETE requests. The Fetch API is powerful, modern, and essential for building dynamic web apps! #JavaScript #FetchAPI #AsyncProgramming #WebDevelopment #Frontend #Promises #AsyncAwait #CodingTips #CleanCode
To view or add a comment, sign in
-
🚀 React 19 is changing the way we write async code — Meet the use() hook! If you’ve ever struggled with fetching data using useEffect, managing loading states, or juggling multiple re-renders — this update is going to blow your mind 💥 React 19 introduces a new built-in hook called use(), which allows you to use asynchronous data directly inside your component. Here’s what it looks like 👇 async function getUser() { const res = await fetch("/api/user"); return res.json(); } export default function Profile() { const user = use(getUser()); return <h1>Hello, {user.name}</h1>; } ✅ No useState ✅ No useEffect ✅ No manual loading states React simply waits until the data is ready, then renders your component with the final result. 🧠 Why this matters This is more than a syntax sugar — it’s a shift in how React thinks about async rendering. React now “understands” async values natively, especially in Server Components (RSC). You write simpler code. React handles the async flow for you. 💡 The Future of React With features like use(), React is becoming more declarative, faster, and smarter. Less boilerplate. More focus on UI and business logic. 🔥 React is evolving. Are you ready to evolve with it? #React19 #JavaScript #WebDevelopment #Frontend #ReactJS #Programming
To view or add a comment, sign in
-
JavaScript doesn’t wait for anything… yet somehow, everything still gets done 😎 Ever wondered how? Master behind the screens — Promises 🔥 In JavaScript, a Promise is like saying — “I don’t have the answer yet, but I’ll get back to you once I do.” It helps JS handle async operations like fetching data, API calls, timers, and more — without blocking the main thread. let's check the below code 👇 const getData = new Promise((resolve, reject) => { const success = true; success ? resolve("✅ Data fetched") : reject("❌ Failed"); }); getData .then(res => console.log(res)) .catch(err => console.log(err)) .finally(() => console.log("Operation complete")); When you run this: First, the promise is pending ⏳ Then it becomes fulfilled ✅ or rejected ❌ But there’s more — Promises can work together too 👇 Promise.all() → Waits for all to finish (fails if one fails) Promise.allSettled() → Waits for all, even if some fail Promise.race() → Returns the fastest one to settle 🏁 Promise.any() → Returns the first successful one 🎯 In short Promises don’t make JavaScript faster. They make it smarter — letting your code do more while waiting for results 💪 #JavaScript #WebDevelopment #Frontend #MERNStack #AsyncProgramming #NodeJS #ReactJS #CodingTips #SoftwareEngineering
To view or add a comment, sign in
-
🚀 Mastering HTTP Methods and the HTTP Headers with Simple JavaScript Examples If you’re diving into API development or front-end integration, mastering HTTP methods and the HTTP header is a must. Here’s a clean and visual breakdown of how to use GET, POST, PUT, PATCH, DELETE, and TRACE with the native fetch() API — no external libraries, just pure JavaScript. Each method has its own purpose in how your app communicates with a server: 🔹 GET → Retrieve data 🔹 POST → Create new data 🔹 PUT → Replace existing data 🔹 PATCH → Update part of data 🔹 DELETE → Remove data 🔹 TRACE → Debug the request path #JavaScript #WebDevelopment #Frontend #Backend #API #Developer #FetchAPI #WebDev #ReactJS #NodeJS #SoftwareEngineering #lifeatsmartx
To view or add a comment, sign in
-
-
Ever wondered why sometimes React just… ignores your state update? No error. No re-render. Just silence. The answer usually comes down to one sneaky word: "mutation". In React, to mutate means to change data directly in memory. Like this 👇 arr.push(4); It works in plain JavaScript — but in React, that tiny change can break how your component updates. Why? Because React doesn’t watch your data. It watches references. When you mutate state directly, React compares old and new references and thinks: “Nothing changed.” So it skips the re-render altogether. The fix is simple — but powerful: Create a new copy of your data instead of changing the original. ✅ Correct way: setItems([...items, 4]); Now React sees a brand-new reference → and updates the UI instantly. Here’s the fun twist: If you’ve used React Query, you’ve probably seen mutate() there too. But that one’s completely different — it means send data to the server (like POST or PUT). Same name. Totally different meaning. 😅 💡 Rule of thumb: If it’s React state → never mutate directly. If it’s React Query → go ahead and mutate(). What’s one React “gotcha” you wish you’d learned earlier? #ReactJS #WebDevelopment #Frontend #JavaScript #ReactQuery #CodingTips #LearnReact
To view or add a comment, sign in
-
💡 Understanding Pure Components in React — With a Simple Real-Life Example Have you ever noticed how React re-renders a component even when the data doesn’t really change? That’s where Pure Components come to the rescue! 🚀 👉 What is a Pure Component? A Pure Component in React is like a smart component that only re-renders when there’s an actual change in the data (props or state). Note:- It helps improve performance by avoiding unnecessary re-renders. 🧠 Real-Life Example: Imagine you have a digital clock app that shows: • Current Time • User’s Name If your name doesn’t change but the time updates every second, React re-renders everything — including your name — again and again. That’s wasteful! 😅 Now, if your Name component is a Pure Component, React will check: > “Has the name changed?” If No, it won’t re-render that part — saving time and improving performance. 💻 Example Code: import React, { PureComponent } from 'react'; class Name extends PureComponent { render() { console.log("Rendering Name..."); return <h2>Hello, {this.props.name}</h2>; } } class Clock extends React.Component { state = { time: new Date().toLocaleTimeString() }; componentDidMount() { setInterval(() => { this.setState({ time: new Date().toLocaleTimeString() }); }, 1000); } render() { return ( <div> <Name name="Amit" /> <p>Time: {this.state.time}</p> </div> ); } } 🧩 In this example, even though the time changes every second, `<Name />` won’t re-render again and again — because it’s a Pure Component and the `name` prop never changes. 🚀 In short: ✅ React.PureComponent = React.Component + automatic “shouldComponentUpdate” check ✅ Improves performance ✅ Ideal for components that depend only on props and don’t change often #ReactJS #WebDevelopment #Frontend #JavaScript #Coding #LearnReact #PureComponent
To view or add a comment, sign in
-
JavaScript Tip: Error Handling Patterns Error handling is crucial for building robust and reliable applications. JavaScript provides several patterns to catch and manage errors effectively. 1. Try…Catch Wrap code that may throw an error: try { let result = riskyOperation(); console.log(result); } catch (error) { console.error('Error caught:', error); } 2. Try…Catch…Finally finally runs regardless of success or failure, ideal for cleanup: try { performTask(); } catch (error) { console.error(error); } finally { console.log('Task finished'); } 3. Promises Catch Handle async errors with .catch(): fetchData() .then(data => console.log(data)) .catch(err => console.error('Fetch error:', err)); 4. Async/Await with Try…Catch Clean syntax for async code: async function fetchData() { try { const response = await fetch('https://lnkd.in/gWKpgMrT'); const data = await response.json(); console.log(data); } catch (error) { console.error('Error:', error); } } Best Practices: Always handle both sync and async errors. Provide meaningful error messages for debugging. Use centralized error logging in production apps. Error handling is not optional—it makes your app resilient, reliable, and professional. #JavaScript #ErrorHandling #AsyncProgramming #Frontend #WebDevelopment #CodingTips #Promises #AsyncAwait #CleanCode
To view or add a comment, sign in
Explore related topics
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development
Well explained