簡體   English   中英

訪問匿名函數之外的變量

[英]Accessing a variable that is outside an anonymous function

我有這個簡單的代碼

 orm: function (req, res) {

    // Send a JSON response


       Noder.query('SELECT * FROM crud ', function(err, results) {
        var all_rows = Noder.query('SELECT count(*) from crud ', function(err, the_rows) {
        return the_rows;
        });

         res.view('noder/orm', {
            layout: 'layout',
            allr:all_rows,
            post:results,
            title: 'This is the hi page title. '
        }); 
      });
   },

我用它來獲取mysql表中的所有行。 但是在該函數中,我想要另一個函數來計算表中有多少行。我的變量var all_rows在我嘗試顯示時顯示未定義。 我該怎么解決這個問題?

這是因為您在返回內部查詢之前訪問all_rows的值。

Noder.query是一個異步函數,因此,它的執行將被延遲,直到查詢本身完成。 同時,當您的內部查詢仍在處理時,您的orm函數將繼續快速向下並調用res.view

要解決此問題,您可以從內部查詢中調用res.view

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM