node.js - 如何在钩子前在摩卡咖啡中使用 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 语句无法运行)。
谢谢你的时间。
解决方案
你这样做是错的。在 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
}
推荐阅读
- android - START_STICKY 前台服务
- django - 如何配置 docker 以使用 django 和 postgres?
- bash - 如何在以 bash 脚本启动的 Ubuntu 中使用 bash 脚本执行命令?
- c# - C# SignalR GetHttpContext / HttpContext 响应不存在
- javascript - 如何查询兄弟节点的现有子节点并遍历它们以检测它是否存在?
- r - 基于双向命中的聚合
- python - 请求、请求 2 和请求 3 之间有什么区别?
- haskell - 数据构造函数haskell中的访问类型字段
- google-chrome - 如何构建像 VSCode 这样的桌面“webapps”
- php - Laravel Lumen - 日志通道