Posts

Showing posts with the label ES6

Using an async iterator on Node.js + S3

There isn't support for  async iterators ( for await...of ) in Node.js v8.9 which is AWS Lambda's runtime. It's shame, as it’s a great feature that allows you to iterate over an iterable that returns as result asynchronously, i.e. retrieving another page from a database, using a compact for loop that feels synchronous but under the covers is actually done asynchronously. Which means, if you want to use a library that written specifically to use it (e.g.  Amazon DynamoDB QueryPaginator ), you have to use an even more verbose syntax. However with a bit of re-purposing you can use a generator function that returns a Promise and if you await each promise given in the loop it will behave like an async iterator.

How to chain an ES6 Promise

Node.js uses async functions extensively, as it based around non-blocking I/O. Each function takes a callback function parameter, which can result in some messy, deeply nested callback functions if you have to call a bunch of async functions in sequence. Promises make these callbacks a lot cleaner. ES6 (or ES2016)  Promise s are a great way of chaining together asynchronous functions so that they read like a series of synchronous statements. There's already some great posts on Promises, 2ality has a good intro to async then detail of the api , so I won't rehash that article. However, after starting to use them for cases more complicated than most examples, it easy to make a few mistaken assumptions or make things difficult for yourself. So here is a more complicated example showing a pattern I like to follow. In this example, I'll use the new Javascript Fetch API , which is an API that returns a Promise, allowing you to make async HTTP calls without having to muck a...