我可以建议您重写代码以实现承诺 - 这样处理起来会容易得多
const {promisisfy} = require('util')
const fs = require('fs')
const readFile = promisify(fs.readFile)
const fileNames = getFilenamesSomehow() // <-- returns array with path, e.g. ["./package.json", "/etc/hosts", "/etc/passwd"]
Promise.all(fileNames.map(name => readFile(name)))
.then(arrayWithFilesContent => analyze(arrayWithFilesContent))
.catch(err => handleError(err))
下一步你可以做什么 - 将代码移动到 async/await 函数中
UPD
假设您只需要读取一个文件,然后将其数据解析为 json 并以某种方式分析结果。
这种情况下你可以做下一步:
readFile(singleFileName)
.then(function (singleFileContent) {
return JSON.parse(singleFileContent)
})
.then(function (singleFileContentInJson) {
return analyze(singleFileContentInJson)
})
.catch(funciton (error) {
//here you can process all errors from functions above: reading file error, JSON.parse error, analyze error...
console.log(error)
})
然后假设您需要分析一堆文件
const fileNames = [...] // array with file names
// this create an array of promises, each of them read one file and returns the file content in JSON
const promises = fileNames.map(function (singleFileName) {
return readFile(singleFileName)
.then(function (singleFileContent) {
return JSON.parse(singleFileContent)
})
})
// promise all resolves (calls callback in 'then') all of promises in array are resolved and pass to then callback array with result of each promise
Promise.all(promises)
.then(function (arrayWithResults) {
return analyze(arrayWithResults)
})
// catch callback calls if one of promises in array rejects with error from the promise - so you can handle e.g. read file error or json parsing error here
.catch(function (error) {
//here you can handle any error
console.log(error)
})
尝试在谷歌上搜索一些文章来阅读 Promise 是如何工作的。
例如。你可以开始表单mdn article