Search code examples
javascriptecmascript-6es6-promisev8

Upon entering a conditional block, is it safe to assume no async action changed the condition?


In this example, I want to return a pending "stop" Promise (1) which deletes an instance's reference to itself (1), and which callee may have pending / queued actions on.

In the case that a stop is currently happening, I want to return that existing, pending promise.

My question is whether or not the initial condition is deterministic and that it will always return a Promise; not undefined.

Since the variable / reference is removed upon completion, I'm curious if an async action could "jump in" between the conditional and the return statement, or if this is forbidden by block execution / precedence.

Thanks

stop () {
    if (this.awaitStop) {
        return this.awaitStop;

    } else {
        this.awaitStop = NativeDevice.video.stop(); // Promise
        return this.awaitStop.then(() => delete this.awaitStop);
    }
}

Solution

  • Non-async functions do not get interrupted. Any callbacks will only be executed after all functions have returned and control flow returns to the "event loop".

    Things would be different if you had an async function:

    async function f() {
      if (foo) { 
        await bar();  // This interrupts f and lets any other code run.
        console.log(foo);  // foo may or may not be the same as before.
      }
    }