在ES6类的构造函数中设置项目

时间:2018-10-12 06:03:02

标签: javascript ecmascript-6 es6-class

我有一个名为Basket的简单类,我想用ajax方法设置产品。请看下面的例子:

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
            }
        });
   }

问题是未设置产品。 resp.products变量以正确的json格式很好地返回了。

1 个答案:

答案 0 :(得分:1)

AJAX是 asynchronous ,这意味着脚本在继续执行下一个任务之前不会等待AJAX​​完成执行(已从正常执行流程中删除)。您正在记录AJAX完成之前的值;您必须将值记录在成功回调中。

相关问题