Open In App

How to make JavaScript wait for a API request to return?

Improve
Improve
Like Article
Like
Save
Share
Report

Prerequisite:Async/Await Function in Javascript

JavaScript is a synchronous language, i.e. JavaScript executes one line of code at a time. It queues the events in action and perform them in order. But in some case, Javascript behaves as asynchronous, such as in AJAX or Axios calls. It makes a call to the API but does not wait for the API to return result, and progresses with the next queued event.

Async/Await Function in JavaScript will provide assistance delaying the program for such API calls. Async and Await function perform on the principle of promises in JavaScript.

  • Async: It makes javascript execute promise based codes as if they were synchronous and return a value without breaking the execution thread. If no value is returned, it wraps the promise and resumes the normal execution.
  • Await: It is used to wait for a promise to return. It is used only inside the async block.

Python Script: We will be making a call to a Python API hosted on the localhost which returns a basic sentence. The code for the API is as follows:

  • Program:




    from flask import Flask, jsonify, request
    from flask_cors import CORS
      
    app = Flask(__name__)
    CORS(app)
      
    @app.route('/test', methods =['GET'])
    def test():
        return jsonify({"result": "Statement 1"})
      
    if __name__ == '__main__':
        app.run(debug = True)

    
    

  • Note: You must have the following packages installed to be able to host this API: flask, jsonify, request, flask_cors. Simply run the python code to start the API on http://127.0.0.1:5000/

    JS Script: The below code is a Javascript program to call the API without Async/Await function.

  • Program:




    function makeGetRequest(path) {
        axios.get(path).then(
            (response) => {
                var result = response.data;
                console.log('Processing Request');
                return (result);
            },
            (error) => {
                console.log(error);
            }
        );
    }
    function main() {
        var response = makeGetRequest('http://127.0.0.1:5000/test');
        console.log(response);
        console.log('Statement 2');
    }
    main();

    
    

  • Expected Output:

    Obtained Output:

    Explanation: This happens because JavaScript called for the API, made it a separate process and then proceeded further. It found console.log(response);, but the response was unsigned by the time, so the console shows undefined. The program progressed and printed ‘Statement 2’. By this time, the API had not even reached the processing statement. This is where Javascript behaves as an asynchronous language. This problem is rectified using Async/Await functions. The corresponding code to establish a promise is given below.

    • Program:




      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() {
          var result = await makeGetRequest('http://127.0.0.1:5000/test');
          console.log(result.result);
          console.log('Statement 2');
      }
      main();

      
      

    • Output:

    Explanation: The async function made the function to continue execution on the same thread without breaking into a separate event. The await keyword marks the point where the program has to wait for the promise to return. Hence, the program waits for the API to return response and then proceeded with the program, therefore, the output is in perfect order as required.



    Last Updated : 10 May, 2020
    Like Article
    Save Article
    Previous
    Next
    Share your thoughts in the comments
    Similar Reads