我正在使用ExpressJS框架的NodeJS在mysql後端工作。我在for循環中運行查詢,我的循環和事後工作取決於查詢的返回值。我對mysql的查詢不太好,所以我通過for循環運行它。 問題是,由於異步[我猜!],for循環在查詢結果出來之前很久就結束了。變量值在NodeJS ExpressJS中變得未定義
這裏是我的代碼:
function search_people_step2(user_id, search_criteria, user_friend)
{
var first_name_friends = [];
var last_name_friends = [];
for(var i = 0; i < user_friend.length; i++)
{
con.query("SELECT first_name, second_name FROM user WHERE userid = ?", user_friend[i],function(err, rows)
{
if(err)
{
//error;
}
else
{
if(rows.length == 0)
{
//nothing gets returned
}
else {
console.log(rows);
first_name_friends[i] = rows[0].first_name;
last_name_friends[i] = rows[0].second_name;
}
}
});
}
現在,我可以得到的值(使用的console.log)查詢語句中,然而,在外面,該值變爲空(未定義),因爲剩下的的代碼已經被計算出來了。
我該如何解決這個問題? 在此先感謝。
你除了如果有一個同步方法來執行查詢。 – n00dl3
如何在JS中編寫同步方法? –
你不能,因爲它取決於sql的實現。你可以使用承諾,如果你真的想返回somthing ... – n00dl3