【问题标题】:How to execute a function after the execution of Nested async/awaits嵌套异步/等待执行后如何执行函数
【发布时间】:2021-03-31 15:58:52
【问题描述】:

我正在处理文件和文本。我正在使用textract 从文档中提取文本并使用amqplib message-broker 发布文本(如果这不是你的事,你仍然可以回答)。我有多个异步/等待函数要运行。在所有文档的文本发布后,我想关闭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, channel, conn);
    console.log("in then from a top level promise");
    // const promise = new Promise(async ()=>{
    //     await startExtraction(job, channel, 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()。提前致谢。

【问题讨论】:

  • textract.fromFileWithPath 转换为“异步”函数。
  • @hoangdv,你的意思是promisify textract.fromFileWithPath 并等待它?我可以这样做,但您能否详细说明它如何帮助我在执行完所有操作后执行功能?
  • await 关键字只作用于thenable object
  • @hoangdv, promosify 仅返回 thenable 对象。我不能等待吗?请详细说明这将如何解决我的问题。我想在我的代码中的 for 循环之后执行一个函数。意思是,我希望它在 for 循环中的所有 async 任务之后执行。
  • 只需“等待”直到所有异步任务完成然后关闭连接。

标签: javascript node.js async-await node-amqplib


【解决方案1】:

好吧,我终于可以解决这个问题了。您可以看到我所做的更改以使其按照@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, channel, conn);
        console.log("in then from a top level promise");
        closeConnection();
      } catch (error) {
        console.error(error)
  }

【讨论】:

    猜你喜欢
    • 2019-12-30
    • 2017-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多