Javascript Promise.all( ) or Promise.settleAll( )

 

Promise.All()

Promise.all() is a JavaScript method that helps you run multiple asynchronous tasks at the same time. Instead of waiting for each task to finish one by one, it runs them together and gives you the result once all tasks are completed successfully. If even one task fails, Promise.all() stops and returns an error.

It is used to execute multiple Promises concurrently and aggregate their results into a single Promise. It resolves with an array of resolved values when all Promises succeed, preserving their original order, and rejects immediately if any Promise fails, following a fail-fast execution model.


    function fetchUser() {
    return new Promise(resolve => {
        setTimeout(() => resolve('User data'), 1000);
    });
    }

    function fetchOrders() {
    return new Promise(resolve => {
        setTimeout(() => resolve('Orders data'), 1500);
    });
    }

    function fetchNotifications() {
    return new Promise(resolve => {
        setTimeout(() => resolve('Notifications data'), 500);
    });
    }

    Promise.all([
    fetchUser(),
    fetchOrders(),
    fetchNotifications()
    ])
    .then(results => {
        const [user, orders, notifications] = results;
        console.log(user);
        console.log(orders);
        console.log(notifications);
    })
    .catch(error => {
        console.error('One of the promises failed:', error);
    });



Think of Promise.all() as: "Run everything together. If one fails, abort the result." It is commonly used to fetch data from multiple APIs in parallel rather than sequentially, which significantly improves performance by reducing total execution time.


Promise.allSettled()

Promise.allSettled() is used to execute multiple asynchronous operations in parallel and wait for all of them to finish, regardless of whether they succeed or fail. Unlike Promise.all(), it never rejects and instead returns the outcome of each Promise.


    async function sendNotifications() {
    const results = await Promise.allSettled([
        sendEmail(),
        sendSMS(),
        sendPush()
    ]);

    results.forEach((res, index) => {
        if (res.status === 'fulfilled') {
        console.log(`Task ${index} succeeded`);
        } else {
        console.error(`Task ${index} failed:`, res.reason);
        }
    });
    }

It runs all async tasks in parallel and gives a complete success/failure report without stopping on errors. “Run everything. Tell me what succeeded and what failed.”

Behavior Comparison Table

FeaturePromise.all()Promise.allSettled()
Waits for all promises❌ No✅ Yes
Stops on first failure✅ Yes❌ No
Rejects✅ Yes❌ Never
ReturnsArray of valuesArray of result objects
Use caseAll-or-nothingBest-effort / partial success



Comments

Popular posts from this blog

React Js + React-Redux (part-2)

React Js + CSS Styling + React Router (part-1)

ViteJS (Module Bundlers, Build Tools)