如果在 GET 请求回调中调用,Node js POST 请求不起作用

Node js POST request not working if called inside GET request callback

我发出获取请求以从一个 API 获取 JSON 数据,并在获取请求的回调中我再次 POST 调用 POST 此数据到另一个 API。这似乎对我不起作用。

var request = require('request');

function startFetchingHistory(postToApp){
request.get(url, function(err, res, body) {
   postToApp(body);
});
}



function postToApp(body) {

 var options = {
uri: 'http://localhost:3079/history',
method: 'POST',
json : body
};

request(options, function(error, response, body) {
console.log(error+response+body);
if (!error && response.statusCode == 200) {
  console.log(body);
} else {
  logger.error('Error from server is' + error);
    }
  });
}

上述方法无效。 "doesn't work",我的意思是 POST 请求回调永远不会被调用。但是,如果我直接调用 postToApp() 方法,POST 请求会成功通过。

可能是因为 postToApp() 需要变量 'request',该变量当前正被位于 (request.get) 中的异步函数使用。

尝试制作另一个 var innerRequest = require('request');并将其用于 postToApp()。

旁注:我认为可能有更好的方法来实现这一点,方法是将正文返回到 startFetchingHistory() 范围内的变量并将其用作 postToApp() 的参数

两个重要概念

  1. request 本质上是异步的
  2. API 当您从主处理程序 return 调用 return 时

如果您查看函数 postToApp,当您调用

request(options, function(error, response, body) {

这会转到您的事件循环,并且函数会执行并完成,而无需等待 post 调用完成。

现在,你要做什么等待函数postToApp完成。最简单的 IMO,如果在 postToApp

的回调中响应您的 API,这是正确的方法
var request = require('request');

function startFetchingHistory(postToApp) {
  request.get(url, function (err, res, body) {
    postToApp(body, (postResponse) => {
      //respond back with the result/error to your API
    });
  });
}



function postToApp(body, callback) {
  var options = {
    uri: 'http://localhost:3079/history',
    method: 'POST',
    json: body
  };
  request(options, function (error, response, body) {
    console.log(error + response + body);
    if (!error && response.statusCode == 200) {
      console.log(body);
      callback(body) // call the function back with the data you want to process;
    } else {
      logger.error('Error from server is' + error);
      callback(error) // call the function back with error to process;
    }
  });
}