0

Having such a simple js DB app:

...
import mysql from 'mysql'
...    
server.get('/Authorize', async (reqObj: Request, resObj: Response) => {

    // check if the access token is already in the DB

    var connection = mysql.createConnection(db_connection);

    connection.connect(function(error) {
        if (error) {
            console.error('----> Authorize - MySql error connecting: ' + error.stack);
            return;
        }

        console.log('----> Authorize - Connected MySql as id ' + connection.threadId);
    });

    ...

    connection.end();

    console.log("----> Authorize - requesting the Discogs server for an request token...")
...

I'm getting the following output:

----> Authorize - requesting the Discogs server for an request token...
----> Authorize - Connected MySql as id ...

My question is WHY does the order of messages is swapped - why does the ...requesting the Discogs server for an request token... line is executed BEFORE the line ...Connected MySql as id. !?

Daros911
  • 435
  • 5
  • 14
  • I'd say it's asynchronous ;) – azro Apr 25 '21 at 10:35
  • The duplicate is about modifying a variable, but the principles are the same. First you say "**When** this connection is established log something" and then you say "**Now** log something else". The latter is going to log before the former because the former doesn't get logged until the connection is established. – Quentin Apr 25 '21 at 10:38
  • @Quentin Ok but how do i know from the code itself if it's asynchronous? – Daros911 Apr 25 '21 at 10:41
  • You can't *know* from looking at the code if something is asynchronous. There are patterns which can suggest it is, knowing that it does something that is typing asynchronous (like interacting with something external) can suggest it is. The documentation is usually a good place to start. – Quentin Apr 25 '21 at 10:44

0 Answers0