1

コードの他の場所で使用するために、SQL クエリの結果を取得しようとしていますが、結果を取得する方法がわかりません。関数をネストしているので、2 回の return 呼び出しで取得しようとしましたが、結果は有効ではありません。

var users = getUsers();


function getUsers(req, res){
  dbConnect(req,res);
  return connection.query('SELECT * FROM USERS', function selectAll(err, rows, fields) {
    if (err) {
        throw err;
    }
    for (var i in rows) {
        console.log(rows[i]);
    }
    return rows;
    dbClose(req,res);
  })
}

ここで何が問題なのですか?

4

1 に答える 1

4

connection.query is an asynchronous function.

rows is only available within the selectAll function. If you'd like to do something with the rows, you need to do it from selectAll.

users will be undefined because the function getUsers itself does not return anything (and can not return rows.

Instead of doing

users = get Users();
doSomethingWithUsers(users);

do this instead:

getUsers();

function getUsers(req, res){
  dbConnect(req,res);
  return connection.query('SELECT * FROM USERS', function selectAll(err, rows, fields) {
    if (err) {
        throw err;
    }
    for (var i in rows) {
        console.log(rows[i]);
    }
    doSomethingWithUsers(rows);
    dbClose(req,res);
  })
}

Or pass a callback function in getUsers that gets passed the result.

于 2013-02-19T22:06:24.367 に答える