如何从 http 请求 NodeJS 中获取变量?

How to get a variable out of http request NodeJS?

我想使用两个 IBM Watson 服务,并将来自两个服务的响应合并到一个变量中,return 将其作为回调。我无法弄清楚如何在 http 请求之外获取 response1 值以将其与来自其他 IBM Watson 服务的 response2 结合起来。

我试过下面的代码,但没有用。我读到我可以使用 promises,但我对此很陌生,不知道该怎么做。

有人可以帮忙吗?

  const AWS = require('aws-sdk');
        var http = require('https');
        exports.handler = (event, context, callback) => {
                var text = JSON.stringify(event.text);
                var options = {
                       method: process.env.method,
                       hostname: process.env.watson_hostname,
                       port: null,
                       path: process.env.path,
                       headers: {
                           'content-type': process.env.content_type,
                            authorization: process.env.authorization,
                           'cache-control': process.env.cache_control,
                           'X-Watson-Learning-Opt-Out': 'true'
                       }
                 };
                   var req = http.request(options, function (res) {
                   var chunks = "";
                   res.on("data", function (chunk) {
                   chunks+ = chunk.toString();;
                      });
                res.on("end", function () { 
                       var response1 = (chunks);
                 //////////////here I need to get reponse2
                 var response2 = IBM2();
              var bothResponses = response1 + response2
              callback(null,bothResponses)
                 
                 
               });
               })
            
  req.write(text);
  req.end()
  
  
  function IBM2(){
              var text = JSON.stringify(event.text);
                var options = {
                       method: process.env.method2,
                       hostname: process.env.watson_hostname2,
                       port: null,
                       path: process.env.path2,
                       headers: {
                           'content-type': process.env.content_type2,
                            authorization: process.env.authorization2,
                           'cache-control': process.env.cache_control,
                           'X-Watson-Learning-Opt-Out': 'true'
                       }
                 };
                   var req = http.request(options, function (res) {
                   var chunks = [];
                   res.on("data", function (chunk) {
                   chunks.push(chunk);
                      });
                res.on("end", function () { 
                       var response2 = JSON.parse(Buffer.concat(chunks));
                  
                   
                   return(response2)
    }

Return 来自 IBM2 函数的承诺,并在调用函数中使用 async await 进行处理。注意 on end 回调之前的 async 关键字。

我已尝试将 Promise 添加到您现有的流程中:

const AWS = require('aws-sdk');
var http = require('https');
exports.handler = (event, context, callback) => {
  var text = JSON.stringify(event.text);
  var options = {
    method: process.env.method,
    hostname: process.env.watson_hostname,
    port: null,
    path: process.env.path,
    headers: {
      'content-type': process.env.content_type,
      authorization: process.env.authorization,
      'cache-control': process.env.cache_control,
      'X-Watson-Learning-Opt-Out': 'true'
    }
  };
  var req = http.request(options, function (res) {
    var chunks = "";
    res.on("data", function (chunk) {
      chunks += chunk.toString();;
    });
    res.on("end", async function () {
      var response1 = (chunks);
      //////////////here I need to get reponse2
      var response2 = await IBM2();
      // validate response2 (in case IBM2 throws error)
      var bothResponses = response1 + response2;
      callback(null,bothResponses)
    });
  });

  req.write(text);
  req.end();


  function IBM2(){
    return new Promise((resolve, reject) =>{
      var text = JSON.stringify(event.text);
      var options = {
        method: process.env.method2,
        hostname: process.env.watson_hostname2,
        port: null,
        path: process.env.path2,
        headers: {
          'content-type': process.env.content_type2,
          authorization: process.env.authorization2,
          'cache-control': process.env.cache_control,
          'X-Watson-Learning-Opt-Out': 'true'
        }
      };
      var req = http.request(options, function (res) {
        var chunks = [];
        res.on("data", function (chunk) {
          chunks.push(chunk);
        });
        res.on("end", function () {
          var response2 = JSON.parse(Buffer.concat(chunks));
          resolve(response2)
        });
        res.on("error", function (err) {
          reject(err);
        });
      })
    });
  }
};

在对您的代码进行任何更改之前,我建议您先了解这些主题。 作为参考,请查看 promises 和 async-await 的概念

Promiese

Async/Await

不知道您是否还有其他错误,但看起来您没有在等待 response2 完成,可能类似于

const response2 = await IBM2():

或者如果你想使用 promises 可能是这样的:

res.on('end', function () {
  var response2 = IBM2().then(
    val => {
      var bothResponses = response1 + val;
      callback(null, bothResponses);
    },
    reject => {
      /* handle rejection here */
    },
  );
});