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

时间:2017-05-29 09:10:53

标签: javascript 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;

为什么不起作用?

3 个答案:

答案 0 :(得分:2)

DatabaseAccess.prototype.getWordPool未返回任何结果。

由于您使用的是异步函数,因此您需要执行以下操作之一:

a)将回调作为参数并使用结果

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

        cb(null, results);
    });
}

回调约定是: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
});

答案 1 :(得分:1)

如果该函数是异步的,您需要将回调传递给find以获得结果:

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

并在main中调用如下:

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

答案 2 :(得分:1)

如果你改成这个就行了:

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;