Open In App

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:



Similar Reads