2017-10-11 32 views
-1

我宣佈變量,我想返回改變變量的值作爲外部函數的值,但目前越來越undefined.Plz提供指導。如何從外部函數在功能全球水平,這最終會內部函數內改變訪問內部函數的性質與JavaScript

function checkResult(req){ 
    let result = true; 
    Reservation.find({result_date: req.body.res_date}, function (err,doc) { 
     if (err) {console.log(err);} 
     else if (reservations) { 
     result = false; 
     console.log(result);  
     } 
    }) 
    console.log("Final:"); 
    return result; // undefined error 
} 
+0

reservation.find做什麼?最重要的是,它是異步的嗎? –

+1

的可能的複製[如何返回從一個異步調用的響應?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – marvel308

回答

0

您應該使用回調。

例如:

function checkResult(req, callback){ 
    let result = true; 
    Reservation.find({result_date: req.body.res_date}, function (err,doc) { 
     if (err) {console.log(err);} 
     else if (reservations) { 
      result = false;  
     } 

     callback(result); 
    }) 
} 

然後使用該函數是這樣的:

checkResult(req, function(result){ 
    console.log(result); // prints the boolean 
}); 
+0

如果示例工作給你,你能接受的答案嗎? :) –

0

Reservation.find看起來採取在其完成時調用的回調。 如果Reservation.find是異步的,那麼checkResult告訴Reservation.find開始執行,然後立即返回result(即undefined)。

換句話說,return result;正在執行之前result = false;,因爲你的匿名函數function (err,doc)內發生的一切了函數執行的流程。

嘗試執行您的回調(在function (err,doc)塊)內需要result任何行動。

編輯:這是Kenji Mukai在下面顯示的內容

相關問題