Skip to content

Instantly share code, notes, and snippets.

@lionel-rowe
Last active February 25, 2019 07:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lionel-rowe/eba3758607ac14dfdfaef37165317586 to your computer and use it in GitHub Desktop.
Save lionel-rowe/eba3758607ac14dfdfaef37165317586 to your computer and use it in GitHub Desktop.
/*
source: https://github.com/zeit/now-examples/blob/3f609858904e7dafbd016a255de325a936cf240f/nextjs-news/lib/get-stories.js
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 stories.map(transform); // ~ Fin
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment