-4

I want to return err or result to postdata function but it's not working.
I am using mongoose database and collection name is 'Demo'.

  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();
}
MarcoS
  • 17,323
  • 24
  • 96
  • 174
  • Check the `Related` bar in the right, the very first link. – zerkms Apr 21 '16 at 10:21
  • 2
    I think he means [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – node_modules Apr 21 '16 at 10:25

2 Answers2

0

Scope; the answer you seek is how can you deal with the scope of variables returned from 'data.save()'.

In JavaScript and other languages, whether they are an interpreted language (php, bash, asp, JavaScript, vbscript, jsp, go etc) or compiled (c, c++, c#, objective-c etc) all make use of scoping.

Variables can be global or local in scope. Your variables 'result' and 'err' in this example are local in scope to the 'data.save()' function, thereby not accessible to the parent function; Demo.prototype.postdata().

On that note I do believe other commenters are correct about this question being s possible duplicate in regards to varible scope.

jas-
  • 1,801
  • 1
  • 18
  • 30
0

I have got answer...

 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");
        }
    })
}