search

Home  >  Q&A  >  body text

javascript - nodejs function returns undefined, I don't quite understand why.

Finally used promise to solve the problem, the code is as follows:
exports.selectByUsername = selectByUsername;
function selectByUsername(username){

var promise = new Promise(function(resolve){
    var sql = "SELECT COUNT(*) count FROM wx_user WHERE username = ?";
    var sqlParams = [username];
    var count;
    co.query(sql,sqlParams,function(err,result){
        if(err){
            return console.log(err.message);
        }
        console.log("------------------------开始查询---------------------");
        console.log(result);
        var str = JSON.stringify(result);
        var json = JSON.parse(str);
        count = json[0].count;
        console.log(count);
        console.log("------------------------查询结束---------------------");
        resolve(count);
    });
});
promise.then(function(value){
    // console.log(value);
    return value;
});
return promise;

}

app.post('/ajax',urlencodedParser,function(req,res){

username = req.body.name;
console.log(username);
var promise = s.selectByUsername(username);
promise.then(function(value){
    console.log(value);
    if(value!==1){
        res.send("用户名不存在");
    }
});

});

Reference document: http://liubin.org/promises-book/

为情所困为情所困2748 days ago895

reply all(3)I'll reply

  • 天蓬老师

    天蓬老师2017-05-16 13:34:46

    The function in the query will not be executed until the query is completed, and at this time the external function has returned, so count will not be assigned a value and is still undefined

    reply
    0
  • 给我你的怀抱

    给我你的怀抱2017-05-16 13:34:46

    Writing it in query will not return count, because the query method is asynchronous

    reply
    0
  • 我想大声告诉你

    我想大声告诉你2017-05-16 13:34:46

    In short, just write the return count in the query.

    reply
    0
  • Cancelreply