Asynchronous constructor

后端 未结 7 1865
轻奢々
轻奢々 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:45

    You can run constructor function with async functions synchronously via nsynjs. Here is an example to illustrate:

    index.js (main app logic):

    var nsynjs = require('nsynjs');
    var modules = {
        MyObject: require('./MyObject')
    };
    
    function synchronousApp(modules) {
        try {
            var myObjectInstance1 = new modules.MyObject('data1.json');
            var myObjectInstance2 = new modules.MyObject('data2.json');
    
            console.log(myObjectInstance1.getData());
            console.log(myObjectInstance2.getData());
        }
        catch (e) {
            console.log("Error",e);
        }
    }
    
    nsynjs.run(synchronousApp,null,modules,function () {
            console.log('done');
    });
    

    MyObject.js (class definition with slow constructor):

    var nsynjs = require('nsynjs');
    
    var synchronousCode = function (wrappers) {
        var config;
    
        // constructor of MyObject
        var MyObject = function(fileName) {
            this.data = JSON.parse(wrappers.readFile(nsynjsCtx, fileName).data);
        };
        MyObject.prototype.getData = function () {
            return this.data;
        };
        return MyObject;
    };
    
    var wrappers = require('./wrappers');
    nsynjs.run(synchronousCode,{},wrappers,function (m) {
        module.exports = m;
    });
    

    wrappers.js (nsynjs-aware wrapper around slow functions with callbacks):

    var fs=require('fs');
    exports.readFile = function (ctx,name) {
        var res={};
        fs.readFile( name, "utf8", function( error , configText ){
            if( error ) res.error = error;
            res.data = configText;
            ctx.resume(error);
        } );
        return res;
    };
    exports.readFile.nsynjsHasCallback = true;
    

    Full set of files for this example could be found here: https://github.com/amaksr/nsynjs/tree/master/examples/node-async-constructor

    0 讨论(0)
提交回复
热议问题