如何等待流完成管道?(节点) [英] How to wait for a stream to finish piping? (Nodejs)
问题描述
我有一个 for 循环的 promise 数组,所以我使用 Promise.all 来遍历它们,然后调用 then.
I have a for loop array of promises, so I used Promise.all to go through them and called then afterwards.
let promises = [];
promises.push(promise1);
promises.push(promise2);
promises.push(promise3);
Promise.all(promises).then((responses) => {
for (let i = 0; i < promises.length; i++) {
if (promise.property === something) {
//do something
} else {
let file = fs.createWriteStream('./hello.pdf');
let stream = responses[i].pipe(file);
/*
I WANT THE PIPING AND THE FOLLOWING CODE
TO RUN BEFORE NEXT ITERATION OF FOR LOOP
*/
stream.on('finish', () => {
//extract the text out of the pdf
extract(filePath, {splitPages: false}, (err, text) => {
if (err) {
console.log(err);
} else {
arrayOfDocuments[i].text_contents = text;
}
});
});
}
}
promise1、promise2 和 promise3 是一些 http 请求,如果其中一个是应用程序/pdf,那么我将其写入流并从中解析文本.但是此代码在从 pdf 中解析测试之前运行下一次迭代.有没有办法让代码等到流的管道和提取完成后再进行下一次迭代?
promise1, promise2, and promise3 are some http requests, and if one of them is an application/pdf, then I write it to a stream and parse the text out of it. But this code runs the next iteration before parsing the test out of the pdf. Is there a way to make the code wait until the piping to the stream and extracting are finished before moving on to the next iteration?
推荐答案
如果没有 async/await,那就太糟糕了.使用异步/等待,只需执行以下操作:
Without async/await, it's quite nasty. With async/await, just do this:
Promise.all(promises).then(async (responses) => {
for (...) {
await new Promise(fulfill => stream.on("finish", fulfill));
//extract the text out of the PDF
}
})
这篇关于如何等待流完成管道?(节点)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!