Skip to content

Instantly share code, notes, and snippets.

@biantris
Created March 21, 2023 10:39
Show Gist options
  • Save biantris/dd81f0311d35db734edc4db1130d677d to your computer and use it in GitHub Desktop.
Save biantris/dd81f0311d35db734edc4db1130d677d to your computer and use it in GitHub Desktop.
code optimization

before

async function loadData() {
  const products = await loadProducts();
  const categories = await loadCategories();
  
  return { products, categories };
}

OK Scenario

async function loadData() {
  const [ products, categories ] = await Promisse.All({
    loadProducts(),
    loadCategories(),
  })
  
  return { products, categories };
}
  • trigger the promises at the same time
  • maybe it will consume too much memory

Processing promises in Batch

  • process all these promises in batch
export async function processPromisesBatch(
  items: Array<any>,
  limit: number,
  fn: (item: any) => Promise<any>,
): Promise<any> {
  let results = [];
  for (let start = 0; start < items.length; start += limit) {
    const end = start + limit > items.length ? items.length : start + limit;

    const slicedResults = await Promise.all(items.slice(start, end).map(fn));

    results = [
      ...results,
      ...slicedResults,
    ]
  }

  return results;
}

Usage

const results = await processPromisesBatch(users, 100, processUser)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment