DEV Community

Discussion on: Challenge: Write your worst program

Collapse
 
arcticshadow profile image
Cole Diffin

I Javascript snippet I wrote recently - I really couldn't be bother properly implementing the consumer (of this func) to be async - so I made the async func sync.

    let done = false
    let result = undefined;

    this.isAuthenticationValid().then((theResult) => {
      done = true;
      result = theResult;
    })

    const asyncChecker = () => {
      setTimeout(() => {
        if(done === true){ // i.e. promise has resolved
          if(result === false){ // i.e. not authenticated
            this.getStrategy().authenticate();
          }
        } else { // promise not yet resolved.
          asyncChecker();
        }
      }, 1000);
    }
    asyncChecker();

N.B. this was in no way production code.

Collapse
 
hrmny profile image
Leah

This is still async

Collapse
 
arcticshadow profile image
Cole Diffin

Appearances can be deceiving. On a technicality yes it's still async. However, from a callers perspective, it operates synchronously. The debate on if this is synchronous or non-synchronous was not the point of me posting this code. If you need a reminder, see the OP title.

Thread Thread
 
hrmny profile image
Leah

For the caller the function returns on the setTimeout call