模块异步函数中的变量范围

variable scope in module asynchronous function

这是我在 Node 的第一周,如果这不是一个简单的问题,我很抱歉。

该代码可以正常工作,并且可以正常工作。但我无法弄清楚如何匹配以 http.get 开头的名称 (url) 和从网站获得的结果。

我发现这个 几乎和我的问题一样,只是这是一个预制函数,所以我无法编辑函数和添加回​​调。

variable scope in asynchronous function

如果我可以 运行 此代码同步或在 http.get 函数中进行回调,一切都会很好。但是我没有技能,不知道你能不能做到。

谢谢 - 罗宾

http = require('http');
function download(name) {
//name is an array whit csgo items names.
for (var i = 0; i < name.length; i++) {

    var marketHashName = getGoodName(name[i]);
    var url = 'http://steamcommunity.com/market/priceoverview/?currency=1&appid=730&market_hash_name=' + marketHashName;

    http.get(url, function (res) {
        var data = "";
        res.on('data', function (chunk) {
            data += chunk;
        });
        res.on("end", function () {

            data = JSON.parse(data);
            var value= 0;
            //get the value in the json array
            if(data.median_price) {
                value = data.median_price;
            }else{
                value = data.lowest_price;
            }

            value = value.substr(5);
            console.log("WEAPON",value);
            //callback whit name/link and value?
            //callback(name,value);
        });
    }).on("error", function () {

    });
}

}

您可以只添加一个回调参数,然后使用最终数据调用它。而且,如果您想将正在处理的特定 marketHashName 传递给回调,那么您可以创建一个闭包来通过 for 循环每次捕获唯一的那个:

http = require('http');

function download(name, callback) {
    //name is an array whit csgo items names.
    for (var i = 0; i < name.length; i++) {

        var marketHashName = getGoodName(name[i]);
        // create closure to capture marketHashName uniquely for each 
        // iteration of the for loop
        (function(theName) {
            var url = 'http://steamcommunity.com/market/priceoverview/?currency=1&appid=730&market_hash_name=' + marketHashName;

            http.get(url, function (res) {
                var data = "";
                res.on('data', function (chunk) {
                    data += chunk;
                });
                res.on("end", function () {

                    data = JSON.parse(data);
                    var value= 0;
                    //get the value in the json array
                    if(data.median_price) {
                        value = data.median_price;
                    }else{
                        value = data.lowest_price;
                    }

                    value = value.substr(5);
                    console.log("WEAPON",value);

                    // now that the async function is done, call the callback
                    // and pass it our results
                    callback(theName, value, data);
                });
            }).on("error", function () {

            });
        })(marketHasName);
    }
}

// sample usage:
download("whatever", function(name, value, data) {
   // put your code here to use the results
});

仅供参考,您可能会发现 request 模块是 http 模块之上的高级功能集,可为您节省一些工作。