嵌套异步/等待执行后如何执行函数

问题描述

我正在处理文件和文本。我正在使用 textract 从文档中提取文本并使用 amqplib 消息代理发布文本(如果这不是您的事,您仍然可以回答)。我有多个异步/等待函数要运行。发布所有文档文本后,我想关闭 amqplib 的连接。这是代码

const startExtraction = async (dir,channel,connection) => {
console.log("Started");
const files = fs.readdirsync(dir);
let i=0
for (let file of files){ 
    const native = `${root}\\${file}`;
    try {
        textract.fromFileWithPath(native,async (err,text) => {
            if (err) {
                console.log(err);
                return;
            }
            const doc = await File.create(payload); // saving the text to database
            channel.sendToQueue(queue,Buffer.from(JSON.stringify(doc)));
            console.log("Sent "+ doc._id);
        });
    }catch(err){
        console.log(err);
    }finally{
        i++;
    }
}
console.log("Done");

}

在这里调用startExtraction

const initiateExtraction = async (job) => {
try {
    const conn = await amqp.connect('amqp://localhost')
    const channel = await conn.createChannel()
    await channel.assertQueue(queue.MLIFY,{ durable: true });
    await startExtraction(job,conn);
    console.log("in then from a top level promise");
    // const promise = new Promise(async ()=>{
    //     await startExtraction(job,conn);
    // });
    // await promise.then(()=>{                      I tried like this(the commented part)
    //    closeConnection(); // this function closes the connection.
    // });
  } catch (error) {
    console.error(error)
  }

}

我不确定我是否接近解决方案。我很难把头放在 asyc/await 上。这个问题的目标是在文本提取和发布到代理后获得一种执行函数 closeConnection()方法。提前致谢。

解决方法

好吧,我终于能够解决这个问题了。您可以看到我所做的更改以使其按照@hoangdv 的建议工作。

const startExtraction = async (dir,channel,connection) => {
console.log("Started");
const files = fs.readdirSync(dir);
let i=0
for (let file of files){ 
    const native = `${root}\\${file}`;
    try {
        const text = await util.promisify(textract.fromFileWithPath)(native); // fetching the text
        const doc = await File.create(payload); // saving the text to database
        channel.sendToQueue(queue,Buffer.from(JSON.stringify(doc)));
        console.log("Sent "+ doc._id);
    }catch(err){
        console.log(err);
    }finally{
        i++;
    }
}

我删除了回调并用承诺替换它并等待它。好像里面的模式应该是一致的。

这里我调用了这两个函数。

const initiateExtraction = async (job) => {
    try {
        const conn = await amqp.connect('amqp://localhost')
        const channel = await conn.createChannel()
        await channel.assertQueue(queue.MLIFY,{ durable: true });
        await startExtraction(job,conn);
        console.log("in then from a top level promise");
        closeConnection();
      } catch (error) {
        console.error(error)
  }