JavaScript - Wait for an API Request to Return in JS Last Updated : 29 Nov, 2024 Suggest changes Share 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 APIFirst, install the required packages by running:npm install express corsCreate 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/AwaitBelow 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/AwaitNow, 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: C chitrankmishra Follow Article Tags : JavaScript Web Technologies Write From Home JavaScript-Misc Explore JavaScript BasicsIntroduction to JavaScript4 min readVariables and Datatypes in JavaScript6 min readJavaScript Operators5 min readControl Statements in JavaScript4 min readArray & StringJavaScript Arrays7 min readJavaScript Array Methods7 min readJavaScript Strings5 min readJavaScript String Methods9 min readFunction & ObjectFunctions in JavaScript5 min readJavaScript Function Expression3 min readFunction Overloading in JavaScript4 min readObjects in JavaScript4 min readJavaScript Object Constructors4 min readOOPObject Oriented Programming in JavaScript3 min readClasses and Objects in JavaScript4 min readWhat Are Access Modifiers In JavaScript ?5 min readJavaScript Constructor Method7 min readAsynchronous JavaScriptAsynchronous JavaScript2 min readJavaScript Callbacks4 min readJavaScript Promise4 min readEvent Loop in JavaScript4 min readAsync and Await in JavaScript2 min readException HandlingJavascript Error and Exceptional Handling6 min readJavaScript Errors Throw and Try to Catch2 min readHow to create custom errors in JavaScript ?2 min readJavaScript TypeError - Invalid Array.prototype.sort argument1 min readDOMHTML DOM (Document Object Model)9 min readHow to select DOM Elements in JavaScript ?3 min readJavaScript Custom Events4 min readJavaScript addEventListener() with Examples9 min readAdvanced TopicsClosure in JavaScript4 min readJavaScript Hoisting6 min readScope of Variables in JavaScript3 min readJavaScript Higher Order Functions7 min readDebugging in JavaScript4 min read My Profile ${profileImgHtml} My Profile Edit Profile My Courses Join Community Transactions Logout Like