+
play
stencil
+
ractive
postgres
aurelia
+
c
+
+
+
protobuf
+
gcp
+
+
+
postgres
hugging
json
+
cargo
jax
+
+
0x
+
0b
+
+
<=
+
node
centos
protobuf
+
django
+
atom
+
+
+
+
jwt
cassandra
++
+
pnpm
+
+
+
ubuntu
sse
scheme
elixir
mongo
+
+
perl
$
+
+
+
nim
eslint
+
+
+
+
+
phoenix
+
+
gentoo
+
axum
scheme
stimulus
+
+
+
solidity
+
marko
s3
+
+
Back to Blog
Understanding Promise.allSettled in Node.js: Managing Tasks Explained
JavaScript NodeJS Promises JavaScript

Understanding Promise.allSettled in Node.js: Managing Tasks Explained

Published Nov 12, 2023

Promise.allSettled is a powerful method in Node.js that allows developers to handle multiple promises in parallel.

4 min read
0 views
Table of Contents

Promise.allSettled is a powerful method in Node.js that allows developers to handle multiple promises in parallel.

Example: API Calls

const axios = require('axios');

const promises = [
    axios.get('https://jsonplaceholder.typicode.com/posts/1'),
    axios.get('https://jsonplaceholder.typicode.com/posts/999'), // This will fail
    axios.get('https://jsonplaceholder.typicode.com/posts/2')
];

Promise.allSettled(promises)
    .then(results => {
        results.forEach((result, index) => {
            if (result.status === 'fulfilled') {
                console.log(`Promise ${index + 1} succeeded:`, result.value.data);
            } else {
                console.log(`Promise ${index + 1} failed:`, result.reason.message);
            }
        });
    });

Example: File Operations

const fs = require('fs').promises;

const files = ['file1.txt', 'file2.txt', 'file3.txt'];
const readPromises = files.map(file => fs.readFile(file, 'utf8'));

Promise.allSettled(readPromises)
    .then(results => {
        results.forEach((result, index) => {
            if (result.status === 'fulfilled') {
                console.log(`File ${files[index]} content:`, result.value);
            } else {
                console.log(`Failed to read ${files[index]}:`, result.reason.message);
            }
        });
    });

Example: Database Queries

const mongoose = require('mongoose');

const queries = [
    User.findById('123'),
    Order.find({ userId: '123' }),
    Product.find({ available: true })
];

Promise.allSettled(queries)
    .then(results => {
        const [userResult, ordersResult, productsResult] = results;
        
        if (userResult.status === 'fulfilled') {
            console.log('User:', userResult.value);
        }
        
        if (ordersResult.status === 'fulfilled') {
            console.log('Orders:', ordersResult.value);
        }
        
        if (productsResult.status === 'fulfilled') {
            console.log('Products:', productsResult.value);
        }
    });

Example: Image Processing

const sharp = require('sharp');

const images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
const resizePromises = images.map(image => 
    sharp(image)
        .resize(200, 200)
        .toFile(`resized-${image}`)
);

Promise.allSettled(resizePromises)
    .then(results => {
        results.forEach((result, index) => {
            if (result.status === 'fulfilled') {
                console.log(`Successfully resized ${images[index]}`);
            } else {
                console.log(`Failed to resize ${images[index]}:`, result.reason.message);
            }
        });
    });

Conclusion

Promise.allSettled is an invaluable tool for handling multiple asynchronous operations where you need to know the outcome of all promises, regardless of whether they succeed or fail.