将来自request.post的bodyhtml响应保存/消费到nodejs中的全局变量中

问题描述

我想将body的内容保存到全局变量returnData中,以便可以将其返回给外部函数。但是,只有当我在回调中console.log时,它才起作用。数据不会保存到全局变量中。

    var returnData; // This is where I want to store the output of request.post


    function getDataFromPostRequest() {
      request.post(
        {
          url: "http://example.com",formData: {x: "y"},},function optionalCallback(err,httpResponse,body) {
          console.log(body) // this is working
          returnData = body;

        }
      );
    }

    console.log("returnData ",returnData); // This is undefined

解决方法

也许您可以做到:

var returnData; // This is where I want to store the output of request.post

function getDataFromPostRequest() {
  request.post(
    {
      url: "http://example.com",formData: {x: "y"},},function optionalCallback(err,httpResponse,body) {
      console.log(body) // this is working
      returnData = body;
      console.log("returnData ",returnData);
    }
  )
}