javascriptnode.jsserver-side-scripting

Node js - Synchronous execution of functions through loop


I have a code like the following

function getData()
{
   for(var i=0; i<someLength; i++)
   {
       if(i===0)
       {
          response = callApi(someValue[i]);
       }
       else if(i===1)
       {
          responseInsert = callWebSocket(response, someValue[i]);
       }       
   }
}
function callApi(insertData)
{
  axios({
  method: 'post',
  url: 'http://localhost:1130/services/request',
  data: insertData,
  headers: { 'content-type': 'application/xml;charset=utf-8' }
  }).then(function (response) {
  console.log(response);
  retVal = true;
  return retVal;
  }).catch(function (error) {
  console.log(error);    
 });
}

In this, response is needed for callWebsocket function with a array's value, that should be achieved through loop. But callWebSocket function gets called before the response comes due to the asynchronous nature of node js. But I have a use case to use server side scripting and I choose node js. Any help to execute the functions synchronously with the loop in place will save me.


Solution

  • You need to modify the callApi method a bit. Try this:

    async function getData()
    {
       for(var i=0; i<someLength; i++)
       {
           if(i===0)
           {
              response = await callApi(someValue[i]);
           }
           else if(i===1)
           {
              responseInsert = callWebSocket(response, someValue[i]);
           }       
       }
    }
    function callApi(insertData)
    {
      return axios({
      method: 'post',
      url: 'http://localhost:1130/services/request',
      data: insertData,
      headers: { 'content-type': 'application/xml;charset=utf-8' }
      });
    }