如何从模块返回Node.js中的数组

一直未定义“main.js”:

var dbAccess = require('../dao/dbAccess'); dbaInstance = new dbAccess(); var wordPool = dbaInstance.getWordPool(); console.log (wordPool); 

和“dbAccess.js”包含:

 var DatabaseAccess = function() {} DatabaseAccess.prototype.getWordPool = function () { RoundWord.find({},'words decoys', function(err, wordPoolFromDB) { if (err) throw err; //console.log(wordPoolFromDB); -working ok return (wordPoolFromDB); }); } module.exports = DatabaseAccess; 

为什么它不工作?

DatabaseAccess.prototype.getWordPool没有返回任何结果。

由于您正在使用asynchronousfunction,因此您需要执行以下其中一项操作:

a)以callback为参数并调用callback结果

 DatabaseAccess.prototype.getWordPool = function (cb) { RoundWord.find({}, 'words decoys', function(err, results) { if (err) { return cb(err, null); } cb(null, results); }); } 

callback约定是: cb(error, results...)

b)使用承诺

 DatabaseAccess.prototype.getWordPool = function () { return RoundWord.find({}, 'words decoys', function (err, results) { if (err) { throw err; // however you might want to sanitize it } return results; }); } 

为了消费这个结果,你需要把它作为一个承诺

 databaseAccess.getWordPool() .catch(function (err) { // process the error here }) .then(function (results) { // something with results }); 

它会工作,如果你改变这个:

 var dbAccess = require('../dao/dbAccess'); dbaInstance = new dbAccess(); dbaInstance.getWordPool(function(wordPool){console.log (wordPool);}); 

和:

 var DatabaseAccess = function() {} DatabaseAccess.prototype.getWordPool = function (cb) { RoundWord.find({},'words decoys', function(err, wordPoolFromDB) { if (err) throw err; //console.log(wordPoolFromDB); -working ok cb(wordPoolFromDB); }); } module.exports = DatabaseAccess; 

如果函数是asynchronous的,你需要传递一个callback来得到结果:

 DatabaseAccess.prototype.getWordPool = function (callback) { RoundWord.find({},'words decoys', function(err, wordPoolFromDB) { if (err) throw err; callback(err, wordPoolFromDB); }); } 

主要调用如下:

 dbaInstance.getWordPool(function (err, wordPool) { console.log (wordPool); // wordPool is only available inside this scope, //unless assigned to another external variable }); // cannot access wordPool here