简体   繁体   English

如何在钩子前在摩卡咖啡中使用 async/await?

[英]How do I use async/await in a mocha before hook?

I am using node's util.promisify to try and await an fs.readFile result inside a helper function, but the second readFile is never called and I always get a timeout error.我正在使用节点的util.promisify尝试在帮助程序 function 中等待fs.readFile结果,但从未调用过第二个 readFile,并且我总是收到超时错误。

From what I can see I am using await correctly, according to the Mocha docs and this blog post that explains the promisify utility function.根据Mocha 文档和解释 promisify 实用程序 function 的博客文章,从我所看到的情况来看,我正在正确使用 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
  }
})

The timeout error is the standard "timeout exceeded... ensure done() is called or ensure Promise resolves".超时错误是标准的“超时...确保完成()被调用或确保 Promise 解决”。 I have noticed that the console will output "got dic data" if the first readFile is reading the.dic file, but if a swap the readFile operations, the console output is "got aff data".我注意到如果第一个 readFile 正在读取 .dic 文件,控制台将 output “获取 dic 数据”,但如果交换 readFile 操作,则控制台 output 是“获取 aff 数据”。

This would suggest that for some reason only the first readFile is being executed, but I have no idea why the first readFile would block the second read file from being executed (and thus the return statement from ever being run).这表明由于某种原因,只有第一个 readFile 正在执行,但我不知道为什么第一个 readFile 会阻止第二个读取文件被执行(因此 return 语句无法运行)。

Thanks for your time.谢谢你的时间。

You're doing it wrong.你这样做是错的。 After promisifying, your readFile function will return a Promise instead, and you can use async/await to handle this.承诺后,您的readFile function 将返回 Promise,您可以使用 async/await 来处理此问题。 If you use callback then you shouldn't need to promisify.如果您使用回调,那么您不需要承诺。

Here's your loadDictionary function written with async/await.这是您使用 async/await 编写的loadDictionary function。

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM