2017-06-22 134 views
1

要么我误解了BlueBird和它的promisify东西是如何工作的,或者我在这里做错了什么。我有一个导出一个函数的“上传处理程序”。这个函数有一个回调PromisifyAll - 回调函数不是函数

上传处理程序看起来像这样(简化):

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 
} 

在我的路由器我promisify处理程序是这样的:

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) 
      }) 
    } 

我在做什么错?

+0

你在哪里调用这个函数'processSourceStrings'? –

+1

你的switch语句应该有一个'break' - 如果匹配''.json''的话,那么它和''.po''就会运行。 –

+0

请向我们展示您调用此功能的代码。 – JLRishe

回答

2

uploadHandler.processSourceStrings(fileInformation)是对基于常规回调的函数的调用,这需要回调作为第二个参数。

Promise.promisifyAll

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)