Asynchronous constructor

后端 未结 7 1916
轻奢々
轻奢々 2020-12-01 00:07

How can I best handle a situation like the following?

I have a constructor that takes a while to complete.

var Element = function Element(name){
            


        
7条回答
  •  旧时难觅i
    2020-12-01 00:39

    One thing you could do is preload all the nuclei (maybe inefficient; I don't know how much data it is). The other, which I would recommend if preloading is not an option, would involve a callback with a cache to save loaded nuclei. Here is that approach:

    Element.nuclei = {};
    
    Element.prototype.load_nucleus = function(name, fn){
       if ( name in Element.nuclei ) {
           this.nucleus = Element.nuclei[name];
           return fn();
       }
       fs.readFile(name+'.json', function(err, data) {
          this.nucleus = Element.nuclei[name] = JSON.parse(data); 
          fn();
       });
    }
    

提交回复
热议问题