1

Is this the right way to use a function that returns a promise which resolves with either true or false inside an if condition?

if(functionName().then(function(data){return data})){
    //execute code
}
  • 1
    It's not the right way since it will return a promise which is always truthy, and the if will always execute the code. – evolutionxbox Jan 20 '22 at 10:51
  • @evolutionxbox But I am also attaching a .then call inside, will that not return the data the function's promise resolved with? – Gaurav Agarwal Jan 20 '22 at 10:53
  • 1
    You're supposed to have the `if` block inside the `then` callback – nick zoum Jan 20 '22 at 10:53
  • `data` will not be accessible outside the `then` – evolutionxbox Jan 20 '22 at 10:55
  • Can you please share a snippet on how to have a function as an if condition which returns a promise that resolves(always) with either a true or a false? – Gaurav Agarwal Jan 20 '22 at 10:58
  • 2
    If you want to run some code when the result of the promise you can use: `functionName().then(function (data){ if (data){ /*execute code*/ }}` or `if(await functionName())` (check browser support) – nick zoum Jan 20 '22 at 10:59

0 Answers0