Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
The actual functionality isn't anything special - it just gets data about news
stories for a typical hacker-news-clone demo app.
What I like is how this really short snippet shows off so many really nice
features of modern JavaScript. This is the snippet I'd show to rebut someone
claiming "JavaScript is a poorly-designed language created by Brendan Eich in
10 days".
import { transform } from "./get-item";
import fetchData from "./fetch-data";
export default async function(
// `async` functions are really nice syntactic sugar that allows writing
// asynchronous code in a way that "looks" synchronous
type = "topstories",
{ page = 1, max = 30 } = {}
// default parameters along with destructuring - caller can provide e.g.
// `{ page: 2 }` as options, and `max` will still default to `30`
) {
const start = max * (page - 1);
const end = start + max;
const ids = await fetchData(type);
// necessary first step before we can proceed, otherwise we don't know what
// story IDs are needed; `await` treats this as if the request is synchronous,
// yet is non-blocking
const stories = await Promise.all(
ids.slice(start, end).map(id => fetchData(`item/${id}`))
// `Promise.all` fires off all the requests asynchronously, but waits for all
// to complete before resolving. This means we only wait the time of the
// single longest request, rather than the sum of all request times.
// old-school `XMLHttpRequest`s with `onload` callbacks could do the same job,
// but would require a lot of messy logic to check whether all requests had
// completed or not, and would be a lot harder to reason about. Naturally,
// polyfils are available for legacy browsers.
return; // ~ Fin
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment