2017-06-22 80 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)