4

我第一次从事 NodeJs 项目。现在我被困在函数通过 JS 返回值并获取值以在 express 中使用。

var dbitems = "before fn";
function refreshData(callback) {
        db.open(function (err, db) {
            if (!err) {
                db.collection('emp').find().toArray(function (err, items) {
                    dbitems = items;
                    callback(JSON.stringify(items));
                });
            }
            else {
                console.log("Could not be connnected" + err);
                dbitems = {"value":"not found"};
            }
        });

    }
}


refreshData(function (id) { console.log(id); }); 

此函数从 refreshData 中完美检索值并写入控制台。但我需要的是使用检索到的值通过“returnedData”从这个函数发送到 express html 文件

exports.index = function (req, res) {
    var valrs = refreshData(function (id) {
        console.log(JSON.parse(id)); ---this again writes data perfectly in the console
    });
    console.log(valrs); -------------------but again resulting in undefined
    res.render('index', { title: 'Express test', returnedData: valrs });
};

任何帮助,将不胜感激。

谢谢和问候,幸运。

4

1 回答 1

5

您需要在数据库请求完成后呈现它。所以它需要从回调中调用。

exports.index = function (req, res) {
    refreshData(function (id) {
        res.render('index', { title: 'Express test', returnedData: JSON.parse(id) });
    });
};

它是异步的,所以你不能只是按顺序排列值,需要通过回调。

于 2012-09-11T04:35:43.113 回答