Control Which Code Stops with Async/Await

13.9k views Asked by At

Can you stop code outside of the async function using await? However, I don't want all code to stop. I want to control what code will run.

I think there might be a solution, something like this:

var isAsyncRunning = false;
var currentPromise;
async function asyncFunc(){
    isAsyncRunning = true;
    //Do some code here
    currentPromise = promise; //promise was defined inside the code
    await promise;
    promise.then(function(){
        isAsyncRunning = false;
    });
}
async function anotherFunction(){
    if(!isAsyncRunning){
        await currentPromise;
    }
    //Do some other code here
}

However, I have a lot of functions and don't want to apply this to every single function that I have.

Is there a better solution? If not, is there anything I can do to make this less time-consuming?

1

There are 1 answers

5
bman On BEST ANSWER

I think your understanding of Promises and async/await is not correct. When you make a function async, the await keyword before a promise make sure that code execution will pause until the promise fulfilled or rejected. Your code can be simplified:

var currentPromise;

async function asyncFunc(promise){
    // Do some code here
    return await promise;
}

function anotherFunction(){
    asyncFunc(currentPromise);
}

When we are calling return await promise, the execution engine waits in a non-blocking way until the promise fulfilled or rejected, and then it returns the output to the anotherFunction function.

Note: If you want to run promises in a sequence you can use reduce function in bluebird or this method, if you prefer vanilla javascript.

Pausing code execution

From your latest comment to the original question, I understand that you want to pause the execution of your program. First, you need to understand that stopping the Javascript execution in a blocking way is not possible. Javascript is a single-threaded programming language that uses event loop to handle concurrency. You can never stop the entire engine for an operation. Otherwise, the program will freeze. In a thread-based programming language, programmers use threads to implement concurrency.

In Javascript, however, you can pause the execution in a non-blocking way using async / await. For example:

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms))
}

async function main() {
  await sleep(1500)
  console.log('Hello world with delay!')
}

main()

If I understand correctly, in your case you'd like to pause the execution based on a user input. You can implement any type of logic that you want. For example, the following program wait for the user to press the RETURN key:

function waitForUserInput(keyCode) {
  return new Promise(resolve => 
    document.addEventListener('keydown', (event) => {
      if (event.keyCode === keyCode) resolve()
    }
  )
}

async function main() {
  await waitForUserInput(13)
  console.log('Thank you for your submission!')
}

main()

In this example, the promise will not be resolved until the keyCode is pressed, and nothing will be logged into the console. Note, that waitForUserInput will not stop the Javascript engine. The engine will continue executing any other code and respond to UI events.