类构造函数中的异步数据加载 [英] Asynchronous data loading in class constructor

查看:95
本文介绍了类构造函数中的异步数据加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例:

var readBackend = function(){
    var deferred = q.defer();
    readData().then(function(data) {
         deferred.resolve(data);
      })
    return deferred.promise;
}

class Test {
    constructor(){
        readBackend().then(function(data) {
            this.importantData = data;
        })
    }

    someFunc() {
        //iterate over important data, but important data is defined
        //promise didnt resolved yet
    }

}

var test = new Test();
test.someFunc(); //throws exception!

当我调用<$ c时,是否有任何方法可以确保构造函数启动对象属性$ c> someFunc ?

我想到的唯一方法就是创建 init 函数,它将返回promise,但是,每次我使用我的类时,我都会依赖init函数来正常工作

The only way which comes to my mind is creating init function, which will return promise, but then, everytime I use my class, I would rely on init function to work properly

推荐答案


当我调用 someFunc 时,有没有办法确保对象属性是由构造函数启动的?

Is there any way to ensure, that object properties are initiated by constructor, when I call someFunc?

不重组您的代码。你不能让你的构造函数执行异步操作并期望你的同步方法能够工作。

Not without restructuring your code. You cannot have your constructor perform asynchronous operations and expect your synchronous methods to work.

我看到两种可能的解决方案:

I see two possible solutions:

1。有一个静态方法加载数据并返回类的新实例:

1. Have a static method which loads the data and returns a new instance of your class:

class Test {
    static createFromBackend() {
      return readBackend().then(data => new Test(data));
    }

    constructor(data){
      this.importantData = data;
    }

    someFunc() {
      // iterate over important data
    }
}

Test.createFromBackend().then(test => {
  test.someFunc();
});

这可确保在创建实例时数据可用,并且您可以保留类的API同步。

This ensures that the data is available when the instance is created and you can keep the API of the class synchronous.

2。将承诺存储在对象上:

2. Store the promise on the object:

class Test {
    constructor(){
      this.importantData = readBackend();
    }

    someFunc() {
      this.importantData.then(data => {
        // iterate over important data
      });
    }
}

当然如果 someFunc 应该返回一些内容,这也需要它返回一个promise。即你的类的API现在是异步的。

Of course if someFunc is supposed to return something, that would require it to return a promise as well. I.e. the API of your class is asynchronous now.

这篇关于类构造函数中的异步数据加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆