Home > database >  Async Function handling different from node js v12 to v16
Async Function handling different from node js v12 to v16

Time:12-08

This is my code:

const pool = require('pg');

dbConfig = {};

async function getClient(dbConfig) {
    const pool = new Pool(dbConfig);
    pool.connect().then(() => console.log('connected'))
        .catch(err => console.error('connection error', err.stack));
    return pool;
}

async function getDBConnection() {
    const client = await getClient(dbConfig);
    await client.connect(function(err){
        if (err) {
          console.error('could not connect to postgres', err);
        }     
      });
    return client;
}

async function main() {
    const client = await getDBConnection();
    const query = "SELECT * FROM table limit 10";
    let response = "NO";

    await client.query(query, [])
                    .then(res => response = res.rows)
                    .catch(e => console.log(e.stack));
                console.log("DEBUG: ", client);
    console.log(response);
    return "***";
}

main().then(res => console.log(res));

If I run this code with nodeV12 it is waiting for main() method to complete but If I run this nodev16 it is not waiting for main() method to complete it is immediately completing with main() method promise pending in background.

This is causing my lambda functions to fail. Anyone knows whether anything major changed from nodev12 to nodev16 in the async functions are handled.

Thank you.

CodePudding user response:

async function main() {
    new Promise(async (resolve, reject)=> {
    const client = await getDBConnection();
    const query = "SELECT * FROM table limit 10";
    let response = "NO";

    await client.query(query, [])
                    .then(res => response = res.rows)
                    .catch(e => {console.log(e.stack); reject('exception_description')});
                console.log("DEBUG: ", client);
    console.log(response);
    resolve("***");
}
}

then you can use main().then(e=>console.log(e));

CodePudding user response:

My best guess is it is something with the library you're using. This code works fine:

const wait = (ms) => new Promise(resolve => setTimeout(resolve, ms))


async function main() {
  console.log('waiting...')
  await wait(2000)
  console.log('Done!')
}

main().then(() => console.log('main() finished'))
  1. getClient() - creates a pool and connects, but will return before the promise completes because it isn't awaited
  2. getDBConnection() - also calls connect and awaits it, but if the library takes a function with an 'err' argument, it seems very strange that it returns a promise...
  • Related