繁体   English   中英

异步 Function 处理不同于 node.js v12 到 v16

[英]Async Function handling different from node js v12 to v16

这是我的代码:

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));

如果我使用 nodeV12 运行此代码,它正在等待 main() 方法完成,但如果我运行此 nodev16,它不会等待 main() 方法完成,它会立即完成 main() 方法 promise 在后台挂起。

这导致我的 lambda 函数失败。 任何人都知道是否处理了异步函数中从 nodev12 到 nodev16 的任何重大更改。

谢谢你。

我最好的猜测是它与您正在使用的库有关。 此代码工作正常:

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() - 创建一个池并连接,但会在 promise 完成之前返回,因为它没有等待
  2. getDBConnection() -调用 connect 并等待它,但是如果库采用带有 'err' 参数的 function,它返回 promise 似乎很奇怪......

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM