首页 > 解决方案 > 如何在钩子前在摩卡咖啡中使用 async/await?

问题描述

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

根据Mocha 文档和解释 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
  }
})

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

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

谢谢你的时间。

标签: node.jsasync-awaitmocha.jsfsnode-promisify

解决方案


你这样做是错的。在 Promisifying 之后,你的readFile函数会返回一个 Promise,你可以使用 async/await 来处理它。如果您使用回调,那么您不需要承诺。

这是您loadDictionary使用 async/await 编写的函数。

const loadDictionary = async (filename) => {
    const dict = {}

    try {
        const data = await readFile(`dictionaries/${filename}.dic`, 'utf8');
        if (data) {
            dict.dic = data
            console.log('got dic data')
        }
    } catch (err) {
        console.log(err)
    }

    try {
        const data = await readFile(`dictionaries/${filename}.aff`, 'utf8');
        if (data) {
            dict.aff = data
            console.log('got aff data')
        }
    } catch (err) {
        console.log(err)
    }

    return dict
}

推荐阅读