我正尝试从word文档中提取纯文本,使用word-extractor (https://www.npmjs.com/package/word-extractor)将其转换为csv。
不幸的是,csv是在从文档中提取数据之前创建的。我刚开始使用async/await,但这似乎是最好的选择。不幸的是,我正在努力将我的回调函数包装在一个promise中(我想)。
var WordExtractor = require("word-extractor");
var extractor = new WordExtractor();
let value = '';
// array of paths to files
const files = glob.sync('./desktop/docs/**/*.doc');
// loop through files
for (let item of files) {
// The object returned from the extract() method is a promise.
let extracted = extractor.extract(item);
// I need this part to finish before anything else happens.
function extractDocs() {
return new Promise((resolve, reject) => {
extracted.then(function(doc) {
value = doc.getBody(); //takes around 1s
});
});
}
// async await function
async function test() {
return await extractDocs();
}
test()
//rest of the code that writes a csv from the data extracted from docs
对于这个措辞糟糕的问题,我们深表歉意,并对您的帮助表示感谢。
发布于 2019-04-11 01:39:58
由于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
中。
发布于 2019-04-11 00:41:15
使用以下内容:
async function extractDocs() {
let promise = new Promise((resolve, reject) => {
extracted.then(function(doc) {
value = doc.getBody(); //takes around 1s
});
});
let result = await promise; // wait till the promise
return result
}
要在代码之后运行,请使用.then()
extractDocs()
.then(console.log)
.catch(console.error)
https://stackoverflow.com/questions/55617247
复制相似问题