0

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.

5
  • 1
    Have callApi return a Promise and then await it Commented Nov 23, 2018 at 7:52
  • Can you please provide a sample code? - @CertainPerformance Commented Nov 23, 2018 at 7:54
  • Hard to say without knowing what callApi is currently Commented Nov 23, 2018 at 7:55
  • Updated - Using axios, I think it already returns a promise.- @CertainPerformance Commented Nov 23, 2018 at 8:00
  • wouldnt a simple callback work for you? var myCallback = function(data) { console.log('got data: '+data); }; var usingItNow = function(callback) { callback('get it?'); }; Commented Nov 23, 2018 at 8:00

1 Answer 1

2

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' }
  });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.