【问题标题】:How do I wait for the API response in Node JS before executing next line如何在执行下一行之前等待 Node JS 中的 API 响应
【发布时间】:2020-12-21 05:35:46
【问题描述】:

我在 node js 中调用 get API,需要等待响应。响应 Alexa Skill 的输出。

API 代码如下:

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;


这个函数我在另一个js文件中调用:

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

-----更多代码行--------

在执行下一行代码之前,我需要等待此 API 的响应。我怎么做。 问候, 纳文

【问题讨论】:

  • 在运行“下一行代码”之前,您不能等待 setTimeout 完成……也可以在那里使用 Promise - 或者如果 Promise 链对您来说太难,请调查 async/await

标签: javascript node.js api async-await


【解决方案1】:

我会使用异步/等待。

如果您在立即调用的async 函数中运行整个主程序,则可以将await 放在任何返回Promise 的函数之前。

要么:

async function mainProgram() {
  // do stuff
}

mainProgram();

只是

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

您需要一个返回承诺的sleep 函数。我通常只做一个这样的:(但我相信也有地方可以导入一个)

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

然后这样走:

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

上面混合并匹配了 then/catch 和 async/await。你也可以这样做:

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

如果你不想使用异步等待

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);

只需将您想做的事情放入then

在原版中,您设置了一个每个人都可以使用的speechText 变量,但在这里我只是将值传递给了下一个。所以我去掉了你拥有的then,它只会传递它收到的相同值。

【讨论】:

    猜你喜欢
    • 2020-05-25
    • 1970-01-01
    • 2018-11-09
    • 2017-11-24
    • 1970-01-01
    • 2012-12-23
    • 1970-01-01
    • 2022-12-01
    • 1970-01-01
    相关资源
    最近更新 更多