Tarik Curto Tarik Curto - 2 months ago 7
Javascript Question

Wait Callback and our result data to take another proccess out of this function

i have this class (product).

var Product = function () {
this.products = [];
this.priceFrom = null;
this.priceTo = null;
this.countDone = 0;
};
Product.prototype = {
constructor: Product,

getProductsByPriceRange: function (priceFrom, priceTo) {
var xhrUrl = "<?= base_url('market/products/xhr_product_price_range') ?>";
var xhrData = {price_from: priceFrom, price_to: priceTo};
var xhrType = "json";

var UtilsClass = new Utils();
UtilsClass.xhrConnection(xhrUrl, xhrData, xhrType, function (data) {
/* MY DATA IS HERE */
});

},

buildList:function (products) {
for (var i = 0; i < products.length; i++) {
var product = products[i];
console.log("product");
}
},

buildOne: function (product) {

}
};

/*....more classes */


And another piece of code (out of product class):

var fromPrice = data.from;
var toPrice = data.to;

var ProductClass = new Product();

var lastCountDone = ProductClass.countDone;

ProductClass.priceFrom = fromPrice;
ProductClass.priceTo = toPrice;
var myProducts = ProductClass.getProductsByPriceRange(ProductClass.priceFrom, ProductClass.priceTo);


My question is... can i wait callback of UtilsClass.xhrConnection (in first piece) and use generated data of callback in second piece of code (out of first piece).

Any ideas would be very valuable to me. Thank you!

Answer
var Product = function () {
    this.products = [];
    this.priceFrom = null;
    this.priceTo = null;
    this.countDone = 0;
};
Product.prototype = {
    constructor: Product,

    getProductsByPriceRange: function (priceFrom, priceTo) {
        var xhrUrl = "<?= base_url('market/products/xhr_product_price_range') ?>";
        var xhrData = {price_from: priceFrom, price_to: priceTo};
        var xhrType = "json";

        var UtilsClass = new Utils();
        return new Promise(function(resolve, reject){
            UtilsClass.xhrConnection(xhrUrl, xhrData, xhrType, function (data) {
            /* MY DATA IS HERE */
                resolve(data)
             });

        });

    },

    buildList:function (products) {
        for (var i = 0; i < products.length; i++) {
            var product = products[i];
            console.log("product");
        }
    },

    buildOne: function (product) {

    }
};

While calling,

var fromPrice = data.from;
            var toPrice = data.to;

            var ProductClass = new Product();

            var lastCountDone = ProductClass.countDone;

            ProductClass.priceFrom = fromPrice;
            ProductClass.priceTo = toPrice;
            var myProducts = ProductClass.getProductsByPriceRange(ProductClass.priceFrom, ProductClass.priceTo).then(function(data){%your data will be available here%});