Monday, 24 April 2017

Run a mongoose query synchronously using async package

I wanna check whether a username is existed or not. I have to run it synchronously.

function notExisted(string) {
    var username = '';

    //STEP 1: check if any user is existed with the givven username, and asign a value to username var.
    User.findOne({'username': string}, function (err, result) {
      if (err) {
        req.flash('error', 'An error occured.');
        res.redirect("back");
      } else {
        if (!result === null) {
          username = result.username;
        } else {
          username = null;
        }
      }
    });

    // STEP 2: based on username varibale return false(if founded) or true(if not founded)
    // if any user has founded, the username variable would be the username. Otherwise it would be null.
    if (username === null) {
      return true;
    } else {
      return false;
    }
  }

As you see step 1 and 2 should run one after another. Do you know how to run that 2 steps synchronously by async library or any better approach? Thanks in advance.



via Joseph

No comments:

Post a Comment