Node.js - asynchronous module loading

后端 未结 4 1571
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-04 07:35

Is it possible to load a Node.js module asynchronously?

This is the standard code:

var foo = require(\"./foo.js\"); // waiting for I/O
foo.bar();
         


        
4条回答
  •  失恋的感觉
    2020-12-04 08:22

    Andrey's code below is the simplest answer which works, but his had a small mistake so I'm posting the correction here as answer. Also, I'm just using callbacks, not bluebird / promises like Andrey's code.

    /* 1. Create a module that does the async operation - request etc */
    
    // foo.js + callback:
    module.exports = function(cb) {
       setTimeout(function() {
          console.log('module loaded!');
          var foo = {};
          // add methods, for example from db lookup results
          foo.bar = function(test){
              console.log('foo.bar() executed with ' + test);
          };
          cb(null, foo);
    
       }, 1000);
    }
    
    /* 2. From another module you can require the first module and specify your callback function */
    
    // usage
    require("./foo.js")(function(err, foo) {
        foo.bar('It Works!');
    });
    
    /* 3. You can also pass in arguments from the invoking function that can be utilised by the module - e.g the "It Works!" argument */
    

提交回复
热议问题