【发布时间】: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,你的意思是
promisifytextract.fromFileWithPath并等待它?我可以这样做,但您能否详细说明它如何帮助我在执行完所有操作后执行功能? -
await 关键字只作用于
thenable object。 -
@hoangdv,
promosify仅返回thenable对象。我不能等待吗?请详细说明这将如何解决我的问题。我想在我的代码中的for循环之后执行一个函数。意思是,我希望它在 for 循环中的所有async任务之后执行。 -
只需“等待”直到所有异步任务完成然后关闭连接。
标签: javascript node.js async-await node-amqplib