Madhu
Madhu

Reputation: 3

Nodejs, How do I wait until the previous post request is completed

Nodejs, How do I wait until the previous post request is completed. Below is the Snippet:

var data ="xxxx"
let XMLHttpRequest1 = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest1();
xhr.withCredentials = true;
xhr.open("POST", https://corpqa.sts.xxxx.com/adfs/oauth2/token);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(data);
console.log("Execution Order 1");
xhr.addEventListener("readystatechange",  function() {
  if(this.readyState === 4) {
    console.log("Execution Order 2");
    //console.log(this.responseText);

  }
});
console.log("Execution Order 3");

In NodeJS, below is the Output of the above code:

Execution Order 1
Execution Order 3
Execution Order 2

How do I make code to WAIT for response, execute this.readyState ===4. before it proceed to execute console.log("Execution Order 3").

Expected Output

Execution Order 1
Execution Order 2
Execution Order 3

Upvotes: 0

Views: 183

Answers (3)

danh
danh

Reputation: 62676

Make a promise-ified version of the http request. It can take an optional authToken param.

const XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;

// return a promise to post data to url
async function post(url, data, authToken) {
  const request = new XMLHttpRequest();
  
  requst.open("POST", url);
  request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
  if (authToken) {
    request.withCredentials = true;
    // request.setRequestHeader( ...set an auth header with authToken
  }
  request.send(data);

  return new Promise((resolve, reject) => {
    request.addEventListener("readystatechange", () => {
      console.log("during the request");
      if (request.readyState === 4 && request.status === 200) resolve();
    });
    // todo: error handling
  });
}

Call it like this:

async function orderOfOperationTest() {
  const data ="xxxx"
  const url = "https://corpqa.sts.xxxx.com/adfs/oauth2/token"
  console.log("before the credential request");
  const authToken = await post(url, data); // notice 'await'
  console.log("after the credential request");
  // now pass authToken as the 3rd param to the next call of 'post()'
}

Upvotes: 1

novice2ninja
novice2ninja

Reputation: 471

Use async/await.
For example:

  1. firstTask()
  2. await secondTask()
  3. thirdTask()
    The execution will wait for the 'secondTask' to finish before it executes the third task.

async function doSomething() {
  try{
    firstTask();
    await callAPI(options); // options with POST operations
    thirdTask();
  }catch(error){
    console.log("error occured ", error);
  }
}

Upvotes: 0

j.f.
j.f.

Reputation: 194

Javascript is a synchronous language. It will execute all the lines and store those callbacks functions in the internal queue until it it called.

// the second parameter define the callback function. 
xhr.addEventListener("readystatechange",  function() {
      if(this.readyState === 4) {
        console.log("Execution Order 2");
        //console.log(this.responseText);
    
      }
    });

In order to have a non-blocking waiting of readyState == 4, u will need to put it inside the callback function like this.

xhr.addEventListener("readystatechange",  function() {
      if(this.readyState === 4) {
        console.log("Execution Order 2");
        //console.log(this.responseText);
        console.log("Execution Order 3");
    
      }
    });

Upvotes: 0

Related Questions