2017-04-25 7 views
-1

ユーザ名が存在するかどうかを確認します。 私はそれを同期して実行する必要があります。非同期パッケージを使用して同期的にmongooseクエリを実行します。

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; 
    } 
    } 

ご覧のとおり、ステップ1と2は順番に実行する必要があります。 asyncライブラリまたはそれ以上の方法で2ステップを同期して実行する方法を知っていますか? ありがとうございます。

+0

は_ _「私は同期的にそれを実行しなければなりません」。どうして?短い答え:できません。 – robertklep

答えて

1

は、私がテストしていませんが、以下のコードを使用しますが、これは滝のための非同期モジュールを使用する方法である: -

let async = require('async'); 
async.waterfall([ 
    function(callback) { 
      User.findOne({'username': string}, function (err, result) { 
       if (err) { 
        callback(true, null); 
       } else { 
        if (!result === null) { 
         username = result.username; 
        } else { 
         username = null; 
        } 
        callback(null, username); 
       } 
      }); 
    }, 
    function (username, callback) { 
      if (username === null) { 
       callback(null, true) 
      } else { 
       callback(null, false) 
      } 
    } 
], function (err, result) { 

    if (err) { 
      req.flash('error', 'An error occured.'); 
      res.redirect("back"); 
    } else { 
      console.log(result);// gives you true/false 
    } 
}) 
+0

または、最善の方法は、ユーザー名を確認するためのミドルウェアを持つことです、このように、メインコードの複雑さは少なくなります。 – rroxysam

関連する問題