Skip to content

Instantly share code, notes, and snippets.

@andygarfield
Last active October 29, 2021 17:15
Show Gist options
  • Save andygarfield/f5059950365568d2b9fcb280a8213ab6 to your computer and use it in GitHub Desktop.
Save andygarfield/f5059950365568d2b9fcb280a8213ab6 to your computer and use it in GitHub Desktop.
Dealing with errors in Promise.all

Dealing with errors in Promise.all

Promise.all stops execution if any of the Promises have an uncaught error.

async function wait(ms) {
    return new Promise((resolve) => {
        setTimeout(resolve, ms);
    });
}

const p1 = new Promise(
    async (resolve, reject) => {
        await wait(1000);
        resolve(1);
    }
)

const p2 = new Promise(
    async (resolve, reject) => {
        reject(new Error("noooooo"));
    }
)

// will stop when p2 rejects
await Promise.all([p1, p2]).then(result => console.log(result))  // result: undefined

In order to allow the execution of the other promises to continue, you have to catch the errors and deal with them.

async function wait(ms) {
    return new Promise((resolve) => {
        setTimeout(resolve, ms);
    });
}

function logError(err) {
    return console.error(err)
}

const p1 = new Promise(
    async (resolve, reject) => {
        await wait(1000);
        resolve(1);
    }
).catch(logError);  // catch the error

const p2 = new Promise(
    async (resolve, reject) => {
        reject(new Error("noooooo"));
    }
).catch(logError);  // gotta catch 'em all

// will log the error in p2 and then wait for p1 to finish
await Promise.all([p1, p2]).then(result => console.log(result))  // result: [1, undefined]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment