Serhii Shliakhov
Serhii Shliakhov

Reputation: 2769

How do I use array each with async/await?

How do I check that every element pass the test if a test is async and can throw an error

const exists = async () => {//can throw an error}
const allExists = [12, 5, 8, 130, 44].every(exists);

Upvotes: 1

Views: 3774

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074949

You can't use synchronous methods like every with functions that do asynchronous work, because the synchronous method won't wait for the asynchronous result. It's possible to write an async every, though:

async function every(array, callback) {
    for (const element of array) {
        const result = await callback(element);
        if (!result) {
           return false;
        }
    }
    return true;
}

Note that because it relies on asynchronous information, it too delivers its result asynchronously. You have to await it (or use .then/.catch, etc.).

That version works in series, only calling the callback for the second entry when the callback for the first has finished its work. That lets you short-circuit (not call the callback for later entries when you already know the answer), but may make it take longer in overall time. Another approach is to do all of the calls in parallel, then check their results:

Promise.all(array.map(callback))
.then(flags => flags.every(Boolean))
.then(result => {
    // ...`result` will be `true` or `false`...
});

Upvotes: 5

Related Questions