Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to make POST call to an API using Axios.js in JavaScript ?
Next article icon

JavaScript - Wait for an API Request to Return in JS

Last Updated : 29 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

For waiting of an API we must need to use express and nodejs to run the JavaScript code. we will create a simple Node.js-based API using Express that returns a JSON response. This will demonstrate how to make API calls using Async/Await in JavaScript.

Create a Simple Express API

First, install the required packages by running:

npm install express cors

Create a server.js file with the following code:

JavaScript
const express = require('express'); const cors = require('cors');  const app = express(); const PORT = 5000;  app.use(cors())  // API endpoint to return a simple message app.get('/getData', (req, res) => {   res.json({ message: "This is a response from the Express API" }); }); // Default Code when u start server  app.get('/',(req,res)=>{     res.send("hello from the server "); }) // Start the server app.listen(PORT, () => {   console.log(`API is running at http://127.0.0.1:${PORT}`); }); 

JavaScript Example Without Using Async/Await

Below is the code for calling the API without using Async/Await. This will demonstrate the default asynchronous behavior in JavaScript.

  • The fetchDataWithoutAsync function calls the API and immediately moves to the next line, logging 'Statement 2'.
  • Since the API call is asynchronous, console.log('Statement 2') is executed before the API response is received, demonstrating out-of-order execution.
JavaScript
function makeGetRequest(path) {     axios.get(path).then(         (response) => {             var result = response.data;             console.log('Processing Request');             return (result);         },         (error) => {             console.log(error);         }     ); } function main() {     let response = makeGetRequest('http://127.0.0.1:5000/test');     console.log(response);     console.log('Statement 2'); } main(); 

Output:

JavaScript Example Using Async/Await

Now, let’s see how we can fix this issue by using Async/Await.

  • The async keyword ensures that fetchDataWithAsync is asynchronous.
  • The await keyword pauses the execution until the promise (API call) is resolved.
  • The program waits for the API response before logging 'Statement 2', ensuring the correct execution order.
JavaScript
function makeGetRequest(path) {     return new Promise(function (resolve, reject) {         axios.get(path).then(             (response) => {                 var result = response.data;                 console.log('Processing Request');                 resolve(result);             },                 (error) => {                 reject(error);             }         );     }); }  async function main() {     let result = await makeGetRequest('http://127.0.0.1:5000/test');     console.log(result.result);     console.log('Statement 2'); } main(); 

Output:


Next Article
How to make POST call to an API using Axios.js in JavaScript ?
author
chitrankmishra
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • Write From Home
  • JavaScript-Misc

Similar Reads

  • How to set the cursor to wait in JavaScript ?
    In JavaScript, we could easily set the cursor to wait. In this article, we will see how we are going to do this. Actually, it's quite an easy task, there is a CSS cursor property and it has some values and one of the values is wait. We will use the [cursor: wait] property of CSS and control its beha
    3 min read
  • How to Wait n Seconds in JavaScript?
    Here are the various methods to wait n seconds in JavaScript 1. Using setTimeout() FunctionsetTimeout() is an asynchronous function in JavaScript that allows you to run code after a specific amount of time has passed. Since setTimeout() is a method of the window object, you can technically write it
    3 min read
  • How to make POST call to an API using Axios.js in JavaScript ?
    Axios is a promise-based HTTP client designed for Node.js and browsers. With Axios, we can easily send asynchronous HTTP requests to REST APIs and perform create, read, update and delete operations. It is an open-source collaboration project hosted on GitHub. It can be imported in plain Javascript o
    2 min read
  • How to wait for multiple Promises in JavaScript ?
    Waiting for multiple promises in JavaScript involves using Promise.all() or Promise.allSettled() methods. These methods accept an array of promises as input. Promise.all() waits for all promises to either resolve or reject, providing a single promise that resolves with an array of results or rejects
    3 min read
  • 4 Ways to Make an API Call in JavaScript
    API(Application Programming Interface) is a set of protocols, rules, and tools that allow different software applications to access allowed functionalities, and data, and interact with each other. API is a service created for user applications that request data or some functionality from servers. To
    7 min read
  • How to create and write tests for API requests in Postman?
    Postman is an API(utility programming interface) development device that enables to construct, take a look at and alter APIs. It could make numerous varieties of HTTP requests(GET, POST, PUT, PATCH), store environments for later use, and convert the API to code for various languages(like JavaScript,
    3 min read
  • How To Return the Response From an Asynchronous Call in JavaScript?
    To return the response from an asynchronous call in JavaScript, it's important to understand how JavaScript handles asynchronous operations like fetching data, reading files, or executing time-based actions. JavaScript is a single-threaded nature means it can only handle one task at a time, but it u
    3 min read
  • How to use async/await with forEach loop in JavaScript ?
    Asynchronous is popular nowadays because it gives functionality of allowing multiple tasks to be executed at the same time (simultaneously) which helps to increase the productivity and efficiency of code. Async/await is used to write asynchronous code. In JavaScript, we use the looping technique to
    2 min read
  • How to Parse JSON in JavaScript ?
    Parse JSON in JavaScript, accepting a JSON string as input and returning a corresponding JavaScript object with two methods, using JSON.parse() for parsing JSON strings directly and employing the fetch API to parse JSON responses from web APIs. These techniques are crucial for seamless data manipula
    2 min read
  • How to connect to an API in JavaScript ?
    An API or Application Programming Interface is an intermediary which carries request/response data between the endpoints of a channel. We can visualize an analogy of API to that of a waiter in a restaurant. A typical waiter in a restaurant would welcome you and ask for your order. He/She confirms th
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences