如何在上钩之前在Mocha中使用async / await?

时间:2020-07-21 17:24:58

标签: node.js async-await mocha fs node-promisify

我正在使用节点的util.promisify来尝试在辅助函数中等待fs.readFile的结果,但是第二个readFile从未被调用,并且总是会出现超时错误。

根据the Mocha docsthis blog post解释的Promisify实用程序功能,据我所知我正在正确使用await。

// mocha setup.js file
const { readFile } = require('fs')
const { promisify } = require('util')

module.exports = {
  readFile: promisify(readFile)
}
// test-file.js
const { assert } = require('chai')
const { readFile } = require('./setup')
const { CustomWordList, Spelling, Word } = require('../src/classes')
const nspell = require('nspell')

describe('Spelling Class', function () {
  const content = 'A colorful text that should be colorful cleaned during Spelling class instantiation! 1337'
  let dictionary
  let speller
  let obj

  before(async function () {
    this.timeout(5000)
    dictionary = await loadDictionary('en-au')
    speller = nspell(dictionary)
    obj = new Spelling(speller, content)
  })

  it('should assert object is instance of Spelling', function () {
    assert.instanceOf(obj, Spelling)
  })

  // read dictionary aff and dic files from disk and return an dictionary object
  const loadDictionary = async (filename) => {
    const dict = {}
    await readFile(`dictionaries/${filename}.dic`, 'utf8', (err, data) => {
      if (err) console.log(err)
      if (data) {
        dict.dic = data
        console.log('got dic data')
      }
    })
    await readFile(`dictionaries/${filename}.aff`, 'utf8', (err, data) => {
      if (err) console.log(err)
      if (data) {
        dict.aff = data
        console.log('got aff data')
      }
    })
    return dict
  }
})

超时错误是标准的“超时已超过...请确保调用了done()或确保Promise解决”。我已经注意到,如果第一个readFile正在读取.dic文件,则控制台将输出“ got dic data”,但是如果交换readFile操作,则控制台输出将是“ got aff data”。

这表明出于某种原因,只有第一个readFile被执行,但是我不知道为什么第一个readFile会阻止第二个读取文件被执行(从而使return语句无法运行)。

感谢您的时间。

1 个答案:

答案 0 :(得分:1)

您做错了。承诺之后,您的UPDATE Inventory SET Verify = 'D' WHERE Tag_No = txtTag 函数将返回一个Promise,您可以使用async / await来处理它。如果您使用回调,则无需进行承诺。

这是您用异步/等待方式编写的readFile函数。

loadDictionary