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

我尝试了下面的代码,但是没有用。我读到我可以使用诺言,但是我对此很陌生,无法弄清楚该怎么做。

有人可以帮忙吗?



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

最佳答案

IBM2函数返回一个Promise,并在调用函数中使用async await处理。注意结束回调之前的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);
        });
      })
    });
  }
};


在对代码进行任何更改之前,建议您先阅读这些主题。
供参考,请看一下promise和async-await的概念

Promiese

Async/Await

关于javascript - 如何从http请求NodeJS中获取变量?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/61087882/

10-12 00:49
查看更多