Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to write async await code that responds to onkeypress events?

I'd like to write a readKey function that's async, and then await each key being pressed in the browser.

I'd like to build this up into synchronous, normal-looking code that's all based on async-await.

So then I could write a readLine function that does await readKey() until the user hits [enter], and delete the last key if the user hits [back], etc.

And then I could write functions that await readLine(), and write functions that call them, etc.

I just don't know how to bridge the gap between writing a document.onkeypress handler... and putting the keys in that event into some async readKey function that I'd write. In other languages, I could use other multi-threading primitives to get there, but I can't figure out how to in js. I was trying to figure out if there was some way to yield the value, but I can't see how to do that, either.

like image 645
Matt Cruikshank Avatar asked Jun 25 '17 12:06

Matt Cruikshank


People also ask

Does async await make code synchronous?

Async/await statements are syntactic sugar created on top of JavaScript Promises. They allow us to write Promise-based code as if it were synchronous, but without blocking the main thread.

How does async await work in event loop?

An async function can contain an await expression, that pauses the execution of the function and waits for the passed Promise's resolution, and then resumes the async function's execution and returns the resolved value. You can think of a Promise in JavaScript as the equivalent of Java's Future or C# 's Task.

Does async await only work with promises?

Async/Await is used to work with promises in asynchronous functions. It is basically syntactic sugar for promises. It is just a wrapper to restyle code and make promises easier to read and use. It makes asynchronous code look more like synchronous/procedural code, which is easier to understand.

Is async await better than promises?

Promises are one of the best additions to JavaScript because they make handling async code so much easier. Going from callbacks to promises feels like a massive upgrade, but there is something even better than promises and that is async/await.


1 Answers

Yes. Let's break it down:

Is it possible to await a custom thing?

Yes — you can await any Promise. For example, to wait for a timeout:

const timerPromise = new Promise(resolve => setTimeout(resolve, 1000));
await timerPromise;

Is it possible to have a promise for a key press?

Yes — resolve the promise when an event happens.

function readKey() {
    return new Promise(resolve => {
        window.addEventListener('keypress', resolve, {once:true});
    });
}
like image 78
Kornel Avatar answered Oct 23 '22 12:10

Kornel