Thursday 18 May 2017

How should I implement asynchronous function in Javascript with node.js and Mongodb?

So far I have seen that there are setTimeout(),process.nextTick(function) for asynchronous function however I have no clue as to how to use it. I have tried on my code since I need a asynchronous function right now but it will have Can\'t set headers after they are sent. This is my code

var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/myproject';

var updateRecord = function(db, req, callback) {
db.collection('documents').updateMany({ 'Item Description': 
req.body.itemDescrip }, {
    $set: { 'Issued QTY': req.body.issueQty }
}, function(err, results) {
    if (err) return callback(err);
    console.log('Done');
    console.log(results);
    var cursor = db.collection('documents').find({
        'Item Description': req.body.itemDescrip,
        'Issued QTY': req.body.issueQty
    });
    var temp = [];
    cursor.each(function(err, doc) {
        if (err) {
            return callback(err);
        } else{
        console.log('Successfully queried');
        console.log(doc);
        temp.push(JSON.stringify(doc));
        }
    });
    callback(null, temp);
});
};

 module.exports = {
    postCollection: function(req, res) {
    var issueQty = req.body.issueQty;
    var itemDescrip = req.body.itemDescrip;
    MongoClient.connect(url, function(err, db) {
        if(err) {
          res.send(err);
          res.end();
          db.close();
          return;
        }
        updateRecord(db, req, function(err, doc) {
            if(err){
              res.send(err);
            }
            else{
              //setTimeout(function(){
                  res.send(doc);
            //},2000);
            }
            res.end();
            db.close();
        });

    });
}
}

Basically I am trying to implement an asynchronous function such that it will execute the updateRecord first before sending a response down below as right now without the setTimeout, all I get it [] due to executing both simultaneously. This is for my web api which I am testing via postman. Any help is appreciated, thanks!



via Ong Kong Tat

No comments:

Post a Comment