要么我误解了 BlueBird 及其 promisify 的工作原理,要么我在这里做错了什么。我有一个导出一个函数的“上传处理程序”。这个函数有一个回调
上传处理程序看起来像这样(简化):
function processSourceStrings(fileInformation, callback) {
var filePath = fileInformation.path
var fileExtension = path.extname(filePath)
switch(fileExtension) {
case '.json':
processFile(filePath, function(err, result) {
if(err)
callback(err)
callback(null, result)
})
case '.pot':
case '.po':
processFile(err, result) {
if(err)
callback(err)
callback(null, result)
})
}
}
module.exports = {
processSourceStrings: processSourceStrings
}
在我的路由器中,我这样 promise 处理程序:
const uploadHandler = Promise.promisifyAll(require('./process-uploads/upload-handler'))
当该函数在运行时被调用时(当它处理一个文件时)它会在 callback(err)
行抛出一个异常,它说:
TypeError: callback is not a function
这里我从我的 router.js 调用函数:
for(var i=0; i<req.files["sourceStrings"].length; i++) {
var fileInformation = req.files["sourceStrings"][i]
var filePath = fileInformation.path
var targetFilePath = path.join(targetPath, req.files["sourceStrings"][i].filename)
fileInformation.path = targetFilePath
mv(filePath, targetFilePath, {mkdirp: true}).then(uploadHandler.processSourceStrings(fileInformation))
.then(function(result) {
console.log(result)
})
.catch(function(err) {
next(err)
})
}
我做错了什么?
最佳答案
uploadHandler.processSourceStrings(fileInformation)
是对基于常规回调的函数的调用,它需要回调作为第二个参数。
Promisifies the entire object by going through the object's properties and creating an async equivalent of each function on the object and its prototype chain. The promisified method name will be the original method name suffixed with suffix (default is "Async").
所以你可以这样调用 promisified 版本:
uploadHandler.processSourceStringsAsync(fileInformation)
关于javascript - PromisifyAll - 回调不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44699187/