1

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);
1
  • 3
    Use Promise.all to wait for all promises to resolve. Commented Sep 27, 2021 at 12:21

1 Answer 1

5

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`...
});
Sign up to request clarification or add additional context in comments.

4 Comments

This will check every element of the array in sequence. Using Promise.all to check all elements in parallel is probably better
@darthmaim - I was just noting the series/parallel thing in the answer, I realized I'd omitted it. I wouldn't say parallel is necessarily better, it's very situation-dependent. But I should have flagged it up originally.
@T.J.Crowder: "won't wait for the asynchronous result."
Thanks @Andy - Took me four reads -- four -- to finally see it. I may need to up my font size. sigh

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.