Node.js 如何将async await与回调函数一起使用
我正在尝试使用word提取器()从word文档中提取纯文本,并将其转换为csv 不幸的是,csv是在从文档中提取数据之前创建的。我不熟悉async/await,但它似乎是最好的选择。不幸的是,我正在努力将回调函数包装成一个承诺(我想) 对于这个措词不当的问题,我们深表歉意,并感谢您的帮助。请使用以下方法:Node.js 如何将async await与回调函数一起使用,node.js,async-await,Node.js,Async Await,我正在尝试使用word提取器()从word文档中提取纯文本,并将其转换为csv 不幸的是,csv是在从文档中提取数据之前创建的。我不熟悉async/await,但它似乎是最好的选择。不幸的是,我正在努力将回调函数包装成一个承诺(我想) 对于这个措词不当的问题,我们深表歉意,并感谢您的帮助。请使用以下方法: async function extractDocs() { let promise = new Promise((resolve, reject) => { extract
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
}
要在代码运行后运行代码,请使用。然后()
:
由于软件包
word提取器
已经支持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
中!!我必须更改“const value=extracted.getBody();”但是它工作得很好。哎呀,对不起,这类型(:
// 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 function someThing() {
try {
const result = await getSomePromise() // if getSomePromise returns a promise
} catch (e) {
// handle error or rethrow
console.error(e)
}
}