Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Finding the first element of an array that satisfies a condition using an Async function

I have a rather weird issue.
I wish to find the first element of an array that satisfies a condition but the find function must be marked as async because a promise is needed to perform the search.

Please the code below is just a sample. The real code that performs the asynchronous search is not shown. But the below is exactly similar to what I intend to do within the find function

Here is the sample code below

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

async testForVideo() {
    let media=["sampleMedia.png"];
    let video = media.find(async (x) => await x.includes(".mp4"));
    console.log(`Retrived Video=${video}`);
}

To my greatest, the response I keep getting back is this

Retrived Video=sampleMedia.png

This is so weird. I was expecting undefined as the correct result, why is it returning a wrong value instead?

I was expecting

Retrived Video=undefined

Any ideas on why this is the case would be greatly appreciated.

Thank you.

>Solution :

find does not support async callbacks so in your case the callback will always return a promise which is trueish for the find method so it will return the first element of an array.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading