Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Promises miss understand

Hi i have simple code like that:

jQuery(function ($) {
    function Item(val) {
        this.val = val
        var self = this;
        this.generateTrDOM = function () {
            var tr = '<tr>';
            tr += '<td>' + self.val + '</td>';
            tr += '</tr>';
            return tr;
        };
    }

    function ItemsCollection() {
        this.someHandler = $('#some_table_id');
        this.data = [];
        var self = this;


        this.getData = function () {
            return new Promise(function (resolve, reject) {
                $.post(base_url + 'controller/action', {
                    action_type: 'get_items'
                }, function (data) {
                    self.prepareData(data).then(resolve());
                }, "json");
            });
        };
        this.prepareData = function (data) {
            return new Promise(function (resolve, reject) {
                for (var x = 0; x < data.length; x++) {
                    self.data.push(
                        new Item(data[x])
                    );
                }
            });
        };
        this.updateTable = function () {
            for (var x = 0; x < self.data.length; x++) {
                self.someHandler.append(self.data[x].generateTrDOM());
            }

        };
    }

    var data = new ItemsCollection();
    data.getData() //this is done second
        .then(
            data.updateTable(); //this is done first - i dont not want to
        );
});

I want to data.updateTable() took place after the data.getData() after AJAX request but its start before. I read about the promises and in my other project its worked very well.

Which I did not understand. Thanks for some advices.

like image 861
kmad Avatar asked Nov 25 '25 20:11

kmad


1 Answers

This should fix the problem. As jfriend00 said, you have to pass a function reference to then(..). If you pass data.updateTable() to then(..) the function is executed immediately.

var data = new ItemsCollection();
data.getData()
  .then(data.updateTable);
like image 180
Stef Chäser Avatar answered Nov 27 '25 09:11

Stef Chäser



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!