1

Unable to use async-await in array filter!

I tried to create array and iterate using filter to add if a response is success

var awardCodes = [1, 2, 3, 11];

function getPosts() {
    const response = fetch("https://jsonplaceholder.typicode.com/user");
    return response;
}

function test(awardCodes) {
    var arr = awardCodes.filter(checkCode);
    console.log(arr, awardCodes);
}

var checkCode = async (code) => {
    try {
        let res = await getPosts();
        if (res.status == 200) {
            console.log("true");
            return true;
        } else {
            console.log("false1");
            return false;
        }
    } catch (error) {
        console.log("false2");
        return false;
    }
    console.log("false3");
    return false;
}

test(awardCodes);

I expect the output to be an empty array

3
  • You give .filter an async function, which always returns a Promise. Commented Oct 9, 2019 at 14:49
  • Yes, filter, map, forEach etc. Are all calback functions that don't understand Promises. Just use for of etc instead. Commented Oct 9, 2019 at 14:49
  • That checkCode predicate doesn't even make much sense - it takes code as parameter but never uses it within the body. What is the intention here? Commented Oct 9, 2019 at 14:55

1 Answer 1

3

Filter won't wait for your promises to resolve before filtering. Use Promise.all or Promise.allSettled to make your requests in parallel, once they are all done check if the codes are all valid, e.g:

const awardCodes = [1, 2, 3, 11];

async function filterValidCodes(awardCodes) {
  const responses = await Promise.all(
    awardCodes.map(code => fetch(`https://checkcode.com/${code}`))
  );

  return awardCodes.filter((_, i) => responses[i].status === 200);
}

(async () => {
  const validCodes = await filterValidCodes(awardCodes);
})();

It would be simpler and much more efficient to pass the codes as an array to the service though.

Sign up to request clarification or add additional context in comments.

1 Comment

how to modify awardCodes based on each fetch call if fetch is success i want that element to be in awardCodes else it should be removed

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.