Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use Promise with express in node.js?

I am using Promise with Express.

router.post('/Registration', function(req, res) {
  var Promise = require('promise');
  var errorsArr = [];
  function username() {
    console.log("1");
    return new Promise(function(resolve, reject) {
      User.findOne({ username: req.body.username }, function(err, user) {
        if(err) {
          reject(err)
        } else {
          console.log("2");
          errorsArr.push({ msg: "Username already been taken." });
          resolve(errorsArr);
        }
      });
    });
  }
  var username = username();
  console.log(errorsArr);
});

When I log errorsArray, it is empty and I don't know why. I am new in node.js. Thanks in advance.

like image 321
hu7sy Avatar asked Jan 27 '16 10:01

hu7sy


People also ask

How do I use Promise Express?

I am using Promise with Express. router. post('/Registration', function(req, res) { var Promise = require('promise'); var errorsArr = []; function username() { console. log("1"); return new Promise(function(resolve, reject) { User.

How do I use promises in node JS?

A Promise in Node means an action which will either be completed or rejected. In case of completion, the promise is kept and otherwise, the promise is broken. So as the word suggests either the promise is kept or it is broken. And unlike callbacks, promises can be chained.

Does Nodejs have promises?

A Node. js Promise is a placeholder for a value that will be available in the future, allowing us to handle the result of an asynchronous task once it has completed or encountered an error. Promises make writing asynchronous code easier. They're an improvement on the callback pattern and very popular in Node.

How do you use promises instead of callbacks?

Promises are JavaScript objects that represent an eventual completion or failure of an asynchronous operation. A promise is a returned object where you attach callbacks, instead of passing callbacks into a function. the place where you attach the callback after a successful completion of a task is called, . then().


2 Answers

Try the following, and after please read the following document https://www.promisejs.org/ to understand how the 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 already been taken."});
                    resolve(errorsArr);
                }

            });
        });
    }
    username().then(function(data) {
        console.log(data);
        next();
    });
});

You can have other errors also (or things that shouldn't be done that way). I'm only showing you the basic use of a Promise.

like image 109
anolsi Avatar answered Oct 18 '22 21:10

anolsi


router.post('/Registration', function(req, res) {
    return User
        .findOne({ username: req.body.username })
        .then((user) => {
            if (user) {
                return console.log({ msg:"Username already been taken" });
            }
            return console.log({ msg: "Username available." });
        })
        .catch((err)=>{
            return console.error(err);
        });
});

you can write a clean code like this. Promise is a global variable available you don't need to require it.

like image 1
Gokul Thulaseedharan Avatar answered Oct 18 '22 23:10

Gokul Thulaseedharan