Code Explainers

Code explainers tagged #promises

javascript
export async function compressImage(file, { maxWidth = 1600, maxHeight = 1600, quality = 0.8, mimeType = 'image/jpeg' } = {}) {
  const bitmap = await createImageBitmap(file);
 
  let { width, height } = bitmap;

Compressing images in the browser with canvas

canvas image-processing promises
Intermediate 7 steps
typescript
export class Semaphore {
  private available: number;
  private readonly waiters: Array<() => void> = [];
 

Building an async Semaphore in TypeScript

concurrency async-await promises
Advanced 6 steps
typescript
type Task<T> = () => Promise<T>;
 
export class Mutex {
  private queue: Array<() => void> = [];

Building an async mutex in TypeScript

concurrency promises locking
Advanced 7 steps
typescript
type Fetcher<T> = (key: string) => Promise<T>;
 
export class RequestDeduplicator<T> {
  private inFlight = new Map<string, Promise<T>>();

Deduplicating in-flight requests in TypeScript

deduplication promises caching
Intermediate 7 steps
typescript
type AsyncFn<A extends unknown[], R> = (...args: A) => Promise<R>;
 
interface MemoizeOptions<A extends unknown[]> {
  keyFn?: (...args: A) => string;

Memoizing async functions with TTL in TypeScript

memoization generics promises
Advanced 8 steps
javascript
async function mapWithConcurrency(items, limit, worker) {
  const results = new Array(items.length);
  let nextIndex = 0;
 

Bounded-concurrency async map in JavaScript

concurrency async-await promises
Intermediate 7 steps
javascript
const RETRIABLE_STATUS = new Set([408, 429, 500, 502, 503, 504]);
 
function sleep(ms, signal) {
  return new Promise((resolve, reject) => {

Retrying fetch with exponential backoff

retry exponential-backoff abort-signal
Advanced 8 steps
typescript
type RetryOptions = {
  retries?: number;
  timeoutMs?: number;
  baseDelayMs?: number;

Retry with timeout and backoff in TypeScript

promises retry exponential-backoff
Intermediate 10 steps
javascript
import Papa from 'papaparse';
 
const MAX_SIZE = 5 * 1024 * 1024;
 

Validating and parsing CSV uploads in the browser

promises csv-parsing validation
Intermediate 8 steps
javascript
async function* fetchPages(baseUrl, maxPages) {
  let page = 1;
  while (page <= maxPages) {
    const data = await mockFetch(`${baseUrl}?page=${page}`);

Paginated APIs with async generators

async-iterators generators pagination
Advanced 7 steps
javascript
const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';
 

Building a Promise from scratch

promises state-machine microtasks
Advanced 10 steps