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

Setting items in constructor in a ES6 Class

我有一个名为 Basket 的简单 class,我想用 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 格式返回。

AJAX 是 asynchronous 这意味着脚本不会等待 AJAX 在继续执行下一个任务之前完成执行(它是脱离了正常的执行流程)。您正在 AJAX 完成之前记录这些值;您必须在成功回调中记录值。