0

My code is:

let users: number [] = [1, 2, 3]

users.forEach(async (usernr: number) => {
        console.log("nr:" + usernr)

        await connection.query("select count(*) from documents where userid = " + usernr.toString(), "", function (err, result) {
            if (err) {
                console.log("err: ", err, " nr: ",usernr);
                return;
            }

            console.log("result: ", result, " nr: ",usernr);
        });
})

my result is:

nr:1
nr:2
nr:3
result:  [ RowDataPacket { 'count(*)': 10 } ]  nr:  1
result:  [ RowDataPacket { 'count(*)': 20 } ]  nr:  2
result:  [ RowDataPacket { 'count(*)': 30 } ]  nr:  3

I tried make the query with 'await' synchronous, but this not work. Where is my mistake? How can I do this synchron?

I try do envelope the connect.query in a function that return a promise like:

const queryPromise = (
    connection: Connection,
    query: string,
    value: (string | number) []
) => {
    
    return new Promise(async (resolve, reject) => {
        connection.query(query, value, function (err, result) {
            if (err) {
                        console.log("err: ", err, " result: ", result);
                }
                return reject(err);
            }

            return resolve(result);
        });
    });
}

and then

await queryPromise(connection, mySQLString, values)

It not work too!!! :(

Gerd
  • 2,265
  • 1
  • 27
  • 46
  • 5
    `connection.query` does not return a Promise so you can't await it. – tkausl Oct 21 '21 at 16:29
  • 1
    Even if `connection.query` returned a promise, `await` doesn't make it synchronous ... – derpirscher Oct 21 '21 at 16:37
  • Your result is exactly what it should be in this situation. You need to explain what you expect instead. – Tomalak Oct 21 '21 at 16:51
  • 1
    `await` only does something useful when awaiting a promise and in your version of mysql `connection.query()` does not return a promise. In addition, the `.forEach()` loop is not asynchronous-aware either so even if you upgraded to a different version of mysql that does support promises and rewrote the `connection.query()` call to properly use promises, you'd have to also replace the `.forEach()` call with a plain `for` loop so the `await` could pause your loop. – jfriend00 Oct 21 '21 at 17:54
  • @Tomalak you are right. I extend my post. – Gerd Oct 22 '21 at 06:51
  • 1
    @Gerd *"How can I do this synchron?"* is the wrong question to ask and the wrong problem to solve. You *never* (well, 99,9 % of the time) actually want to make asynchronous processes synchronous. Instead I suspect that the asynchronous nature of that DB query is an inconvenience to you in another location, and you're just falling back to the thought "Why can't that behave as if it were synchronous?"*. You'll me much better off adapting that other location to asynchronous code, than trying to make asynchronous code synchronous. – Tomalak Oct 22 '21 at 07:14
  • 1
    In other words, you need to shed some light on the larger context. – Tomalak Oct 22 '21 at 07:15
  • Interesting. You say my point of view is wrong. Maybe. But the alternative is to write very nested code. Bad to read and maintain! :(( – Gerd Oct 22 '21 at 08:11
  • No, the alternative is certainly not to write very nested code. Give more of your context, and I'll try to show you how. – Tomalak Oct 22 '21 at 08:43
  • Now I found an interesting answer. https://stackoverflow.com/q/44004418/1514029 In msql2 package get connect.query a promise and than async should work :) Thanks! – Gerd Oct 22 '21 at 09:07
  • @Gerd Try that, I'll wait here. – Tomalak Oct 22 '21 at 09:24

1 Answers1

0

My mistakes:

  1. bad mysql packages: use mysql2 instead it handle promises correct
  2. bad usage of forEach: forEach don't wait for promises, use for loop instead

correct typescript code:

import mysql, {Connection} from 'mysql2/promise';

const connection: Connection = await mysql.createConnection({
        host: 'localhost',
        user: 'youruser',
        password: process.env.DB_PASS,
        database: 'yourdb'
    });

let users: number [] = [1, 2, 3]

for(let userNr: number = 0; userNr < users.length; userNr++){

        console.log("userNr:" + userNr)

        try {
            const [res] = await connection.query("select count(*) documents where userid = " + userNr.toString(), [])

            console.log("result: ", res, " nr: ",userNr);

        }
        catch (err) {
            console.log("err: ", err, " nr: ",userNr);
            return;
        }
}

Details:

Gerd
  • 2,265
  • 1
  • 27
  • 46