synchronous - node.js database queries in order -


i'd perform queries in order don't know best approach.

let's i'd following :

if (name) {   //first query   db.query({name:name}).exec(function(err,result) {   //save result   }) } if (isempty(result)) {   //make query   db.query({anotherfield:value}).exec(function(err,result) {   //save result   }) } 

should use promises on case?

that example cakephp :

if (!isset($field1)) {   $result = $this->item->find( ... conditions => ... = $field2); } else {   if (!isset($field2)) {     $result = $this->item->find( ... conditions => ... = $field1);   } else {     $result = $this->item->find( ... conditions => ... = $field1 && ... =$field2);     if (empty($result)) {       $result = $this->item->find( ... conditions => ... =$field2);     }   }   } 

if mean "in order" can nest callbacks. passing callbacks classic (non-promise) way structure asynchronous code:

function domultipleasyncthings(name, callback){   if (name) {     //first query     db.query({name:name}).exec(function(err,result) {       if (isempty(result)) {         //make query         db.query({anotherfield:value}).exec(function(err,result) {           //save result         })       } else {         //save result       }     })   } else {     return callback('no name');   } } 

heads up, after more 2 or operations, end in 'callback hell' 100+ lines of nested code, async library helpful this:

var async = require('async'); domultipleasyncthings('plato', function(){   console.log(arguments) });  function domultipleasyncthings(name, callback){   // `callback` passed-in function call after domultipleasyncthings done   // here, function passed in above after 'plato'   async.waterfall([function(done){       done(null, name);     },     firstquery,     secondquery,   ], callback) }  function firstquery(name, done){   if (name) {     // can define , pass callback inline:     db.query({name:name}).exec(function(err,result) {       done(err, result);     })   } else {     done('no name');   } }  function secondquery(result, done){   if (isempty(result)) {     // can pass callback reference:     db.query({anotherfield:value}).exec(done)   } else {     //save result     done();   } } 

Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -