2017-08-04 39 views
-1

我有一個函數來檢查用戶是否是高級用戶。從.then的外部檢查布爾值.then在node.js之外。

this._isPremium(message.member.id, message).then(function(premium, message) { 
    console.log("premium status"+premium); 
}); 


//access premium var outside of then 
if(premium) { 
    console.log("premium user") 
} 

它返回一個布爾(溢價),但我需要訪問然後循環的布爾外檢查它是否是真還是假。

它在迴圈內的回聲很好,我只是無法從那裏得到它。

+1

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

+1

有趣。你爲什麼假設可以用參數調用'onFulfilled'函數? '然後(函數(premium,message){'就像用兩個不同的值解決承諾一樣。 – Jaime

回答

0

你應該響應存儲到一個外部變量,如承諾外使用:

var isPremium; 
this._isPremium(message.member.id, message).then(function(premium, message) { 
    isPremium = premium; 
});  

if(isPremium) { 
    console.log("premium user") 
} 

但是當你正在使用的承諾,你需要確保你將執行代碼的承諾一直只有後解決。你標記的節點,不是假設你正在使用HTTP從節點,您可以使用finally

var isPremium; 
    function callback() { 
     if(isPremium) console.log("premium user"); 
    } 

    this._isPremium(message.member.id, message) 
     .then(function(premium, message) { 
      isPremium = premium; 
     }) 
     .finally(callback); 
0

回報,你想使用(保費)從當時的函數值:

const premium = this._isPremium(message.member.id, message) 
    .then(premium => premium);