2017-06-24 26 views
1

我嘗試使用nodejs的q庫,我使用Q.fcall,然後出現以下錯誤。在q(promise)中,無法讀取未定義的屬性'apply'?

file_path/node_modules/q.js:155 
      throw e; 
      ^
TypeError: Cannot read property 'apply' of undefined 
at Promise.apply (/Users/name/Desktop/Programming/video_tutorial_archive/node_modules/q/q.js:1185:25) 
at Promise.promise.promiseDispatch (/Users/name/Desktop/Programming/video_tutorial_archive/node_modules/q/q.js:808:41) 
at /Users/name/Desktop/Programming/video_tutorial_archive/node_modules/q/q.js:1411:14 
at runSingle (/Users/name/Desktop/Programming/video_tutorial_archive/node_modules/q/q.js:137:13) 
at flush (/Users/name/Desktop/Programming/video_tutorial_archive/node_modules/q/q.js:125:13) 
at _combinedTickCallback (internal/process/next_tick.js:73:7) 
at process._tickCallback (internal/process/next_tick.js:104:9) 

以下是我的代碼:

app.get('/',function(req,res){ 

Q.fcall(sql_query.select_comment(con,comment)) 
.then(function(){ 

    var deferred=Q.defer(); 
    con.query("SELECT * FROM "+table_video, function (err, result) { 
     console.log("step 2 finished"); 
     console.log("comment is "+comment); 
      // if (err) throw err; 
      query_result=result; 
      // deferred.resolve(); 

     // console.log(query_result); 
    }) 
    // return deferred.promise; 

}).then(function(){ 
    console.log("step 3 finished"); 
    console.log("comment is "+comment); 
    console.log(query_result); 

    res.render('index',{ 
       result:query_result, 
       comment:comment.comment 
    }); 
}).done(); 

}); 

我可以Q.defer解決這個問題,但我想,而不是FCALL使用。它更乾淨,沒有deferred.promise和deferred.resolve。

什麼是導致錯誤「無法讀取屬性'應用'未定義」?以及如何解決它?

回答

0

我想你應該分開PARAMS:Q.fcall(sql_query.select_comment, con, comment),就像你會與sql_query.select_comment.call(this, con, comment)

做它無法找到.apply()因爲sql_query.select_comment(con, comment)返回值是不是一個函數。

2

首先,您必須將函數傳遞給Q.fcall()。你從sql_query.select_comment(con,comment)傳遞返回結果,這顯然不是一個函數。

要正確使用Q.fcall(),請將第一個參數作爲要調用的函數傳遞,並且以下參數是要傳遞給該函數的參數。另外,如果你想select_comment仍然綁定到sql_query(我不知道這是否是必需的),那麼你可以使用.bind()是安全的。你可以把所有的一起這樣的:

Q.fcall(sql_query.select_comment.bind(sql_query), con, comment) 

Cannot read property 'apply' of undefined的錯誤是因爲從sql_query.select_comment()返回值是undefined所以當Q.fcall()嘗試使用它.apply()附加的參數,它拋出這個錯誤。

您還有另一個錯誤,因爲您的外部承諾並未等待con.query("SELECT * FROM "+table_video, function (err, result) {})完成。最好的解決方案是隻使用承諾界面來處理所有數據庫功能。然後,您可以從.then()處理程序中返回con.query()的承諾,並且它將自動鏈接到父承諾,並且事情將順序正確。

自己看看發生了什麼事情的Q.fcall()裏面,你可以看一下源爲該函數here on Github

Q.fcall = function (object /* ...args*/) { 
    return Q(object).dispatch("apply", [void 0, array_slice(arguments, 1)]); 
}; 

如果這最終將嘗試在第一個參數調用.apply()Q.fcall()

相關問題