0

Hello i'm new in node js and I definitly need help

Here i need to have access to the result query for a for loop after this but my variable firstresult don't change outside the query loop.

How can i do it ?

            db.query("SELECT * FROM film", function (err, result) {
              if (err) throw err;

                firstresult=result
            });
                console.log(firstresult) ///AFFICHE undefined```
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – derpirscher Jul 24 '22 at 22:40

1 Answers1

0

you have two problems in your code:

  1. using undefined variable (global variable defined too late)
  2. trying too access to early
// database query method is asynchronous
//   * when resolved calling callback with data
//   * use data directly in the callback 
//   * or run another function to process obtained data

db.query("SELECT * FROM film", function (err, result) {
    if (err) throw err;
    console.log(result);
    someOtherFunction(result);
});

someOtherFunction(result) {
    // do whatever you want with result
}
Michal Miky Jankovský
  • 3,089
  • 1
  • 35
  • 36