0

我正在使用 fs.readFileSync 读取 JSON 文件,并且对于获得的每个文档,我正在使用 client.post 进行休息 API 调用。一旦我得到响应,我想将接收到的内容放入另一个 JSON 文件中,该文件是输入 JSON 的副本,除了从 client.post 调用接收到的数据的附加元素。但是可能由于 client.post 的异步性质,我无法将元素添加到输出 JSON。我是 NodeJS 的新手。你能帮我在我失踪的地方吗?下面是代码和数据

数据:

[
    {
        "ticker": "CLYD"
    },
    {
        "ticker": "EGH"
    } 
]

代码:

var fs = require('fs');
var Client = require('node-rest-client').Client;

var data = fs.readFileSync(__dirname + "/data/stocks.json", "utf8");  
processData(data);

function processData (data) {

    var obj = JSON.parse(data);

    for (j = 0; j < obj.length; j++) {

        obj[j].stockInformation = getValuesForTicker (obj[j].ticker.trim());

    }

    var jsonOutput = JSON.stringify(obj,null,'\t');
    fs.writeFileSync(__dirname + "/data/response.json", jsonOutput);

};

function getValuesForTicker (ticker) {

    /**
     * More details and samples at https://www.npmjs.com/package/node-rest-client
     */
    var client = new Client();
    var values;

    // set content-type header and data as json in args parameter
    var args = {
        data: { "ticker" : ticker},
        headers: { "Content-Type": "application/json", "Accept" : "application/json" }
    };

    var responseToRequest = client.post("https://url.providing.response.as.json.content/", args, function (data, response) {
//         parsed response body as js object
        values = JSON.parse(JSON.stringify(data)).price;
    });
    return values;

};
4

1 回答 1

0

由于getValueForTicker进行异步调用以获取数据,它应该在收到数据后调用回调(或者更好的承诺)并且不返回结果(当前undefined在分配值之前返回值)

function getValuesForTicker (ticker, callback) {

    /**
     * More details and samples at https://www.npmjs.com/package/node-rest-client
     */
    return new Promise(function(resolve, reject) {

             var client = new Client();
             var values;

           // set content-type header and data as json in args parameter
            var args = {
              data: { "ticker" : ticker},
              headers: { "Content-Type": "application/json", "Accept" : "application/json" }
           };

          var responseToRequest = 
          client.post("https://url.providing.response.as.json.content/", args, function (data, response) {
         //         parsed response body as js object
             values = JSON.parse(JSON.stringify(data)).price;
             resolve(values)
        });

    };
})

并在异步调用完成后获取数据,您需要调用 then 函数,如下所示:

        getValuesForTicker(obj[j].ticker.trim())
        .then(function(val) {
             obj[j].stockInformation = val
        })

考虑到您是 node.js 的新手,这将很难获得。先花一些时间了解回调和承诺。

于 2017-09-25T18:43:24.107 回答