如何通过回调函数使用异步等待

时间:2019-04-10 16:23:19

标签: node.js async-await

我正在尝试使用word-extractor(https://www.npmjs.com/package/word-extractor)从word文档中提取纯文本并将其转换为csv。

不幸的是,在可以从文档中提取数据之前创建了csv。我是异步/等待新手,但似乎是最佳选择。不幸的是,我努力将回调函数包装在一个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 

对于这个措辞不佳的问题表示歉意,并为您提供任何帮助。

2 个答案:

答案 0 :(得分:3)

使用以下内容:

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)

答案 1 :(得分:1)

由于软件包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中。