简体   繁体   English

如何在执行下一行之前等待 Node JS 中的 API 响应

[英]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.我在 node.js 中拨打 get API 需要等待响应。 Response it the output of Alexa Skill.回复 Alexa Skill 的 output。

Here is the API code:这是 API 代码:

const GetReportOnEmail = function (UserID, ReportName) { 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; } module.exports.GetReportOnEmail=GetReportOnEmail;


This function I am calling in another js file:这个function我是在另一个js文件中调用的:

            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.在执行下一行代码之前,我需要等待这个 API 的响应。 How do I do That.我怎么做。 Regards, Naveen问候,纳文

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 .如果您在立即调用的async function 中运行整个主程序,则可以将await放在返回Promise的任何 function 之前。

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)你需要一个返回 promise 的sleep function。我通常只做一个这样的:(但我确信也有地方可以导入一个)

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

Then go like this:然后 go 这样:

(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.上面的混合和匹配 then/catch 和 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 .把你想做的事情放到then中。

In the original you are setting a speechTex t variable that everybody can use, but here I just passed the value onto the next then.原来你设置了一个每个人都可以使用的speechTex t 变量,但在这里我只是将值传递给下一个 then。 So I got rid of the then that you had, which would have just passed on the same value it received.所以我摆脱了你拥有的then ,它只会传递它收到的相同价值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM