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

问题描述 投票:0回答:2

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

不幸的是,在从文档中提取数据之前创建了csv。我是async / await的新手,但它似乎是最好的选择。不幸的是,我正在努力将我的回调函数包装在一个承诺中(我认为)。

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 

对于措辞严重的问题和任何帮助表示歉意表示赞赏。

node.js async-await
2个回答
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中。


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)
© www.soinside.com 2019 - 2024. All rights reserved.