Asynchronous constructor

后端 未结 7 1913
轻奢々
轻奢々 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条回答
  •  佛祖请我去吃肉
    2020-12-01 00:31

    This is a bad code design.

    The main problem is in the callback your instance it's not still execute the "return", this is what I mean

    var MyClass = function(cb) {
      doAsync(function(err) {
        cb(err)
      }
    
      return {
        method1: function() { },
        method2: function() { }
      }
    }
    
    var _my = new MyClass(function(err) {
      console.log('instance', _my) // < _my is still undefined
      // _my.method1() can't run any methods from _my instance
    })
    _my.method1() // < it run the function, but it's not yet inited
    

    So, the good code design is to explicitly call the "init" method (or in your case "load_nucleus") after instanced the class

    var MyClass = function() {
      return {
        init: function(cb) {
          doAsync(function(err) {
            cb(err)
          }
        },
        method1: function() { },
        method2: function() { }
      }
    }
    
    var _my = new MyClass()
    _my.init(function(err) { 
       if(err) {
         console.error('init error', err)
         return
       } 
       console.log('inited')
      // _my.method1()
    })
    

提交回复
热议问题