-1

I have a simple class named Basket, I want to set my products with ajax method. Please look at the example below:

class Basket
{

    constructor()
    {
        this.products = [];
        this.setProducts();
        console.log(this.products); // still empty
    }

    setProducts()
    {
        var self = this;
        $.ajax({
            'url': getProductsUrl,
            'method': 'GET',
            success: function(resp) {
                console.log(resp.products); // I can see products returned from api
                self.products = resp.products
            },
            error: function(resp) {
                // err
            }
        });
   }

The problem is that products are not set. resp.products variable is returned well and in proper json format.

Martin
  • 1,259
  • 3
  • 17
  • 36
  • If the products are logged, then they *are* assigned to `self`. Why do you say they aren't set? Also, if you're using `Class`, you should use arrow functions instead of `self = this` – CertainPerformance Oct 12 '18 at 06:04
  • 1
    @CertainPerformance products cannot be logged because they are not retrieved _yet_ at that moment – skyboyer Oct 12 '18 at 06:06
  • But your comment says `// I can see products returned from api`. Is that comment actually not true? (if it isn't, best to remove it for clarity) – CertainPerformance Oct 12 '18 at 06:07

1 Answers1

1

AJAX is asynchronous which means that the script does not wait for the AJAX to finish executing before moving on to the next task (it is taken out of the normal execution flow). You are logging the values before the AJAX is finished; you have to log the values in the success callback.

Unmitigated
  • 76,500
  • 11
  • 62
  • 80