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?
I think your understanding of Promises and
async/await
is not correct. When you make a functionasync
, theawait
keyword before a promise make sure that code execution will pause until the promise fulfilled or rejected. Your code can be simplified: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 theanotherFunction
function.Note: If you want to run promises in a sequence you can use
reduce
function inbluebird
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: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:In this example, the promise will not be resolved until the
keyCode
is pressed, and nothing will be logged into the console. Note, thatwaitForUserInput
will not stop the Javascript engine. The engine will continue executing any other code and respond to UI events.