javascript - nodejs function returns undefined, I don't quite understand why.
为情所困
为情所困 2017-05-16 13:32:46
0
3
902

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/

为情所困
为情所困

reply all(3)
Peter_Zhu

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

给我你的怀抱

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

我想大声告诉你

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template