Back to Home
Async

How to Run Promises Sequentially

Use for...of loop with await to run promises in sequence

Quick Answer (2024 ES6+ Way)

javascript
const urls = [url1, url2, url3];
const results = [];
for (const url of urls) {
  const data = await fetch(url);
  results.push(data);
}

Live Example

javascript
async function processSequentially(items) {
  const results = [];
  
  for (const item of items) {
    console.log(`Processing ${item}...`);
    await sleep(1000); // Wait 1 second
    results.push(`Processed: ${item}`);
  }
  
  return results;
}

// Using reduce for sequential promises
async function sequence(tasks) {
  return tasks.reduce(async (promise, task) => {
    const results = await promise;
    const result = await task();
    return [...results, result];
  }, Promise.resolve([]));
}

// Process in batches
async function batchProcess(items, batchSize) {
  const results = [];
  for (let i = 0; i < items.length; i += batchSize) {
    const batch = items.slice(i, i + batchSize);
    const batchResults = await Promise.all(
      batch.map(item => processItem(item))
    );
    results.push(...batchResults);
  }
  return results;
}

Common Variations

With Error Recovery
javascript
for (const task of tasks) {
  try {
    await task();
  } catch (error) {
    console.error('Task failed:', error);
    // Continue with next task
  }
}
Array.reduce Pattern
javascript
const result = await items.reduce(
  async (acc, item) => [...await acc, await process(item)],
  Promise.resolve([])
);

❌ Don't Do This (Outdated Way)

Avoid Promise.all() when order matters

javascript
// DON'T DO THIS if sequential order is required
await Promise.all(urls.map(url => fetch(url)));

Browser Support

Works in all modern browsers (ES2017+)

#async#sequential#promises