Home>
I want to achieve
console.log (
    m_sql (
        "SELECT * FROM accounts WHERE user =?;", ["Jhon"]
    ) .results [0] .mail_address
);


SQL statement with Node.js likem_sql ()Pass it to the function and send the execution result of the SQL statementm_sql ()Receive as the return value of the function.
thism_sql ()I want to make a function.

Where i am stumbling
const mysql = require ("mysql");
const connection = mysql.createConnection ({{
    host: "localhost",
    user: "root",
    password: "toor",
    database: "test"
});
/ * ================================================ ============= * /
function m_sql (code, argv) {
    var ret;
    new Promise ((resolve, reject) =>{
        // Since connection.query is an asynchronous function, we are using a Promise.
        connection.query (code, argv,
            (error, results, fields) =>{
                resolve ({{
                    error: error,
                    results: results,
                    fields: fields
                });
            }
        );
    }). then (data =>{
        ret = data;
        console.log (data);
        // =>SQL statement execution result
        console.log (ret);
        // =>SQL statement execution result
        // Here, the execution result of the SQL statement is safely stored in ret,
    });
    // Here ret is undefined
    console.log (ret);
    // =>undefined
    return ret;
}
console.log (m_sql ("SELECT * FROM auth;"));
// =>undefined
what I want to know
  • How can iretHolds the execution result of the SQL statementreturnCan you do it?
What I researched/tried
  • Pass by reference
    Passing JavaScript by reference was confusing and I couldn't do it.
    There is also an article that passing by reference does not exist.
Environment/version
  • OS Windows 10 Home 64bit
  • Node.js v12.16.1
  • SQL 10.5.5-MariaDB
  • Answer # 1

    PromiseI think there is a misunderstanding about the behavior of.retThe problem I'm having with is "not assigning" instead of "not holding". It may not be intuitive, but this code is processed in the following order:

          function m_sql (code, argv) {
    / * 1 */var ret;// Unassigned
                new Promise ((resolve, reject) =>{
    /*3*/ connection.query (code, argv,
    / * 4 */(error, results, fields) =>{
    / * 5 */resolve ({{
                                error: error,
                                results: results,
                                fields: fields
                            });
                        }
                    );
                }). then (data =>{
    / * 6 */ret = data;// Assigned here
                });
                // Because it is not said "Wait for` Promise` ", it will be skipped so far
    / * 2 */return ret;// Not assigned
            }
            console.log (m_sql ("SELECT * FROM auth;"));// Output in step 2

    To solve thism_sql ()Asynchronize itself (PromiseLet's do it.

    // Make the return value of the function `Promise` by prefixing it with` async`
    async function m_sql (code, argv) {
        // No need for `var ret`
        // Wait for the `Promise` to be resolved by prepending the` await` to the `new Promise`
        const data = await new Promise ((resolve, reject) =>{
            connection.query (code, argv,
                (error, results, fields) =>{
                    resolve ({{
                        error: error,
                        results: results,
                        fields: fields
                    });
                }
            );
        // When you reach here, the completion of `Promise` processing is guaranteed
        // `.then (...)` is unnecessary
        return data;// Can return `data` directly
    }

    Keep in mind when calling this function (asynchronous function)awaitWithPromiseLet's wait for the resolution:

    // Using `await` outside the function is called" Top-level await "
    console.log (await m_sql ("SELECT * FROM auth;"));

    Older node versions (14.7.0 and earlier) don't support Top-level await, so the whole thingasync mainMust be enclosed in a function:

    async function main () {
        // Put the whole process here
        console.log (await m_sql ("SELECT * FROM auth;"));
    }
    main ();

Related articles