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.
await
inside a function that isn't set asasync
- soanotherFunction
is invalid – Olivasreduce
function inbluebird
or if you prefer vanilla javascript use this approach: https://mcmap.net/q/80794/-resolve-promises-one-after-another-i-e-in-sequence – Paleontographyawait
. – Wycoffawait
for a moment. What problem are you trying to solve, and what behavior do you expect? You can't arbitrarily "pause" or "stop" code in JS. JS doesn't have threads (web workers aside). – Joettejoeyprompt
.prompt
stops all code except for the user typing. I want to implement something like that, but I want to control which I stop and which I keep running, – Wycoff