-1

I have a function which checks if a user is a premium user.

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")
}

It returns a boolean (premium), but I need to access the boolean outside of the then loop to check whether it is true or false.

It echos just fine inside the then loop I just can't get it out of there.

abagshaw
  • 6,162
  • 4
  • 38
  • 76
kevin
  • 115
  • 8
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – SimpleJ Aug 04 '17 at 22:16
  • 1
    Interesting. Why are you assuming that `onFulfilled` function can be called with to parameters? `.then(function(premium, message) {` Is like resolving a promise with two different values. – Jaime Aug 05 '17 at 01:49

2 Answers2

0

You should store the response into an outside variable to use outside the promise like:

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

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

But as you are using promises, you need to secure that you'll execute the code only after the promise been resolved. You tagged node, than assuming you're using http from node, you can use the 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

Return the value that you'd like to use (premium) from the then function:

const premium = this._isPremium(message.member.id, message)
    .then(premium => premium);
Andy Gaskell
  • 31,495
  • 6
  • 74
  • 83