05 January 2019

Using async/await in the repl

Javascript lends itself really well to writing asynchronous code, but when you open up the JavaScript console in a web browser or the command-line interpreter in Node, it becomes annoying really fast to test out an asynchronous method and see what it returns.

The async/await pattern lends itself really well to writing code in a repl, and while you cannot use await in top-level JavaScript code, you can in the repl!

In the Chrome JavaScript console, you can just use await:

> await fetch('https://official-joke-api.herokuapp.com/random_joke')
    .then(r => r.json())

{id: 4, type: "general", setup: "What do you call a belt made out of watches?", punchline: "A waist of time."}

With Node 10+ you can do --experimental-repl-await (thanks vsemozhetbyt!):

$ node --experimental-repl-await
> await require('fs').promises.readFile('hi.txt', 'utf8')

'hi!\n'

You can also go ahead and set an alias for node to use this flag by default.

Enjoy!




Interested in working with me at Superset to help shape the future of virtual fitness and to empower people to launch their own businesses online? We’re hiring a full-stack engineer. πŸ’ͺπŸ€“πŸ’» Apply online



Did you find this helpful or fun? paypal.me/mrcoles
comments powered by Disqus

Peter Coles

Peter Coles

is a software engineer living in NYC who is building Superset πŸ’ͺ and also created GoFullPage πŸ“Έ
more »

github · soundcloud · @lethys · rss