Julius S. Julius S. -4 years ago 113
Javascript Question

Why does if(asynchronous.get()) work and is it ok to use it this way

When I use something like


is an asynchronous function, I wonder how this could ever work as the if statement isn't testing anything unless the function returns a value. Somehow I have this in my code and it works so can anyone explain to my why it works and if I should change it.

Edit: My assumption that my function is asynchronous was wrong, so everything is answered now.

Answer Source

The if statement simply checks if the expression evaluates to a truthy value. It seems the function returns a promise, which is a function object, which is a truthy value.

The function will be executed, but you will not be able to process the result this way and the if statement will never be evaluated to false.

You need to wait for the function to resolve a value and then check the value:

asynchronous.get().then(val => {
    if (val) {...}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download