节点.js回调函数不返回值

node.js callback function does not return value

本文关键字:返回值 函数 回调 js 节点      更新时间:2023-09-26

我想将错误或结果返回到postdata函数,但它不起作用。
我正在使用猫鼬数据库,集合名称为"演示"。

  Demo.prototype.postdata = function(username, mobile, image) {
    var data = new conn.Demo({username, mobile, image});
    data.save(function(err, result) {
        if (err) {
            return err;
        } else {
            return result;
        }
    });
    return data.save();
}

Scope;你寻求的答案是如何处理从'data.save()'返回的变量的作用域。

在JavaScript和其他语言中,无论是解释型语言(php,bash,asp,JavaScript,vbscript,jsp,go等)还是编译(c,c ++,c#,objective-c等)都使用范围。

变量的范围可以是全局的,也可以是局部的。此示例中的变量 'result' 和 'err' 在 'data.save()' 函数的范围内是本地的,因此父函数无法访问;Demo.prototype.postdata().

这一点上,我确实相信其他评论者是正确的,这个问题在可变范围方面可能是重复的。

我得到了答案...

 function rawBody(req, res, next) {
    var chunks = [];
    req.on('data', function(chunk) {
        chunks.push(chunk);
    });
    req.on('end', function() {
        var buffer = Buffer.concat(chunks);
        req.bodyLength = buffer.length;
        req.rawBody = buffer;
        next();
    });
    req.on('error', function (err) {
        console.log(err);
        res.status(500);
    });
}
router.post('/:mobile/:username',rawBody,function(req,res){
    if(req.rawBody && req.bodyLength>0){
        var data={
            mobile:req.params.mobile,
            username:req.params.username,
            image:req.rawBody
        }
        content.postdata(data,callback);    
        function callback(data){
            console.log(data);
        }
    }
})
    Demo.prototype.postdata=function(data,callback)
{
    var data=new conn.Demo(data);
    data.save(function(err,result){
        if(err){
            callback(err)
        }else{
            callback("successfully save");
        }
    })
}