Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/37.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js Nodejs导出未返回值_Node.js_Return_Export - Fatal编程技术网

Node.js Nodejs导出未返回值

Node.js Nodejs导出未返回值,node.js,return,export,Node.js,Return,Export,我有一个像这样的nodejs导出 exports.add = function(req){ var newUser = new User({ email: req.body.email, password: req.body.password, }); // Attempt to save the user newUser.save(function(err) { if (err) { r

我有一个像这样的nodejs导出

exports.add = function(req){

    var newUser = new User({
        email: req.body.email,
        password: req.body.password,
    });

    // Attempt to save the user
    newUser.save(function(err) {
        if (err) {
            return true;

        }
        return false;
    });

}
var value = instance.add(req);
但是当我这样调用函数时,它是未定义的

exports.add = function(req){

    var newUser = new User({
        email: req.body.email,
        password: req.body.password,
    });

    // Attempt to save the user
    newUser.save(function(err) {
        if (err) {
            return true;

        }
        return false;
    });

}
var value = instance.add(req);

这里的实例是javascript文件的导入实例,

,正如@Ben Fortune的评论所述,您不能简单地从异步函数调用返回值。您应该使用回调承诺

回调方式为:

exports.add = function (req, callback) {

    var newUser = new User({
        email: req.body.email,
        password: req.body.password,
    });

    // Attempt to save the user
    newUser.save(function(err) {
        if (err) {
            callback(err, null);
        }
        callback(null, newUser.toJSON()) ;
    });

}
然后:

阅读更多内容:如果您愿意,请以方式履行承诺。

可能重复的