返回值以在XMLHttpRequest的范围之外使用

时间:2018-02-02 07:17:31

标签: javascript html

我正在做一个XMLHttpRequest,它在它自己的功能中。我想返回其他函数使用的price1 var。但它似乎在范围内丢失了。以下代码 -



var dataControl = (function () {
    var getPrice = function(sym){
        var xhttp = new XMLHttpRequest();
        var response, price1;
        xhttp.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200) {
                response = JSON.parse(this.responseText);
                price1 = response['Data'];
                price1 = price1[0].open;
                console.log(price1);
                return price1;
            }
        };
        xhttp.open("GET", "https://min-api.cryptocompare.com/data/histominute?fsym=XRP&tsym=USD&limit=60&aggregate=3&e=CCCAGG", true);
        xhttp.send();
    }
    return {
        getItem: function () {
            getPrice();
        }
    }
})();




1 个答案:

答案 0 :(得分:0)

您可以使用Callback Paradigm获取所需的数据

var dataControl = (function () {
    var getPrice = function (cb) {
        cb = (typeof cb === 'function' && cb) || function(){};
        var xhttp = new XMLHttpRequest();
        var response, price1;
        xhttp.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200) {
                response = JSON.parse(this.responseText);
                price1 = response['Data'];
                price1 = price1[0].open;
                console.log(price1);
                // Assuming error first callback paradign
                cb(null, price1);
            }
        };
        xhttp.open("GET", "https://min-api.cryptocompare.com/data/histominute?fsym=XRP&tsym=USD&limit=60&aggregate=3&e=CCCAGG", true);
        xhttp.send();
    }
    return {
        getItem: function (cb) {
            getPrice(cb);
        }
    }
})();

dataControl.getItem(function(err, data){
    if(err){
        // Handle error
        return;
    }
    console.log(data); // Value of price1
});