Поскольку пакет word-extractor
уже поддерживает promise
, вы можете сделать следующее:
// need async function to use await
async function extractDocs() {
// loop through files
// values = []; maybe store individual value if you plan to use it?
for (let item of files) {
// The object returned from the extract() method is a promise.
// since it already returns a promise you can await
// await will pause execution till the promise is resolved, sync like
let extracted = await extractor.extract(item);
const value = extracted.getBody();
// now use value
// values.push[value]
}
// return values so you can use it somewhere
// return values
}
// execute
// extractDocs returns promise, so to use the return value you can do
async function useExtracted() {
const values = await extractDocs(); // values is an array if you've returned
//rest of the code that writes a csv from the data extracted from docs
}
// execute
useExtracted()
Общий синтаксис async/await
:
async function someThing() {
try {
const result = await getSomePromise() // if getSomePromise returns a promise
} catch (e) {
// handle error or rethrow
console.error(e)
}
}
Примечание: await
действует только внутри функции async
, и все, что возвращается функцией async
, также заключено в Promise
.