how to use Promise with express in node.js? -


i using promise express.

router.post('/registration', function(req, res) {   var promise = require('promise');   var errorsarr = [];   function username() {     console.log("agyaaa");     return new promise(function(resolve, reject) {       user.findone({ username: req.body.username }, function(err, user) {         if(err) {           reject(err)         } else {           console.log("yaha b agyaaa");           errorsarr.push({ msg: "username been taken." });           resolve(errorsarr);         }       });     });   }   var username = username();   console.log(errorsarr); }); 

when log errorsarray, empty , don't know why. new in node.js. in advance.

try following, , after please read following document https://www.promisejs.org/ understand how promises work.

var promise = require('promise'); router.post('/registration',function(req,res,next) {     function username() {         console.log("agyaaa");         return new promise(function(resolve,reject) {             user.findone({"username":req.body.username}, function(err,user) {                 if (err) {                     reject(err)                 } else {                     console.log("yaha b agyaaa");                     var errorsarr = [];                     errorsarr.push({"msg":"username been taken."});                     resolve(errorsarr);                 }              });         });     }     username().then(function(data) {         console.log(data);         next();     }); }); 

you can have other errors (or things shouldn't done way). i'm showing basic use of promise.


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -