NAVEEN JAIN
NAVEEN JAIN

Reputation: 11

How do I wait for the API response in Node JS before executing next line

I am calling get API in node js and need to wait for response. Response it the output of Alexa Skill.

Here is the API code:

const GetReportOnEmail = function (UserID, ReportName) {

return new Promise(function(resolve, reject){

    var options = {        
        uri:'https://www.xxxxx/xx/xx',
        method : 'GET'
    };        
    request(options, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            res = body;
            resolve(res);
        }
        else {
            res = 'Not Found';
            reject(res);
        }            
    });       
})  

} module.exports.GetReportOnEmail=GetReportOnEmail;


This function I am calling in another js file:

            setTimeout(function () {
                GetReportEmail.GetReportOnEmail('userID', 'ReportName').then((resp) => {
                    speechText = resp;
                }).catch((error) => {
                    speechText = "some error occurred";
                })
            }, 20000);

-----Further lines of code-------

I need to wait for the response from this API before executing next line of code. How do I do That. Regards, Naveen

Upvotes: 1

Views: 5780

Answers (1)

Alex028502
Alex028502

Reputation: 3814

I would use async/await.

If you run your whole main program in an async function that you call immediately, you can put await before any function that returns a Promise.

either:

async function mainProgram() {
  // do stuff
}

mainProgram();

of just

(async function () {
  // do stuff
})()

You need a sleep function that returns a promise. I usually just make one like this: (but I am sure there is somewhere to import one too)

function sleep(t) {
  return new Promise(function(resolve) {
    setTimeout(resolve, t);
  });
};

Then go like this:

(async function() {
  await sleep(20000);
  const speechText = await GetReportEmail.GetReportOnEmail(
    'userID',
    'ReportName',
  ).catch((error) => {
    return "some error occurred";
  })
  console.log(speechText);
});

the above mixes and matches then/catch and async/await. You can also do it like this:

(async function() {
  await sleep(20000);
  let speechText;
  try {
    speechText = await GetReportEmail.GetReportOnEmail(
      'userID',
      'ReportName',
    )
  } catch (e) {
    speechText = "some error occurred";
  }
  console.log(speechText);
});

if you don't want to use async await

setTimeout(function () {
  GetReportEmail.GetReportOnEmail(
    'userID',
    'ReportName',
  ).catch((error) => {
     return "some error occurred";
  }).then(function(resp) {
     const speechText = resp;
     // do something like
     console.log(speechText);
  });
}, 20000);

Just put the thing you want to do after into a then.

In the original you are setting a speechText variable that everybody can use, but here I just passed the value onto the next then. So I got rid of the then that you had, which would have just passed on the same value it received.

Upvotes: 1

Related Questions