如何将变量传递给请求的回调

How do I pass a variable to request's callback?

本文关键字:请求 回调 变量      更新时间:2023-09-26

我正在使用express和request将网站的html转换为json,然后返回它。例如:

app.get('/live', function(req,_res){
  res = _res;
  options.url = 'http://targetsite.com';
  request(options,parseLive);
});
function parseLive(err, resp, html) {
  var ret = {status:'ok'};
  -- error checking and parsing of html --
  res.send(ret);
}

目前,我正在使用全局变量来跟踪返回调用,但是当同时发出多个请求时,这将失败。因此,我需要某种方式将来自 express 的返回调用与其请求中的回调相匹配。

我该怎么做?

使用闭包。

将变量传递给函数。从该函数返回要传递给request的函数。

app.get('/live', function(req,_res){
  options.url = 'http://targetsite.com';
  request(options,parseLiveFactory(res));
});

function parseLiveFactory(res) {
    function parseLive(err, resp, html) {
      var ret = {status:'ok'};
      -- error checking and parsing of html --
      res.send(ret);
    }
    return parseLive;
}