0

我正在处理文件和文本。我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, 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()这个问题的目标是在文本提取并发布到代理后获得一种执行功能的方法。提前致谢。

4

1 回答 1

0

好吧,最后我能够解决这个问题。您可以看到我所做的更改以使其按照@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)
  }
于 2021-03-31T07:58:52.893 回答