Skip to content
Advertisement

Using an async function in Array.find()

It seems I’m unable to use an async function as the first argument to Array.find(). I can’t see why this code would not work what is happening under the hood?

JavaScript

https://codesandbox.io/s/zk8ny3ol03

Advertisement

Answer

Simply put, find does not expect a promise to be returned, because it is not intended for asynchronous things. It loops through the array until one of the elements results in a truthy value being returned. An object, including a promise object, is truthy, and so the find stops on the first element.

If you want an asynchronous equivalent of find, you’ll need to write it yourself. One consideration you’ll want to have is whether you want to run things in parallel, or if you want to run them sequentially, blocking before you move on to the next index.

For example, here’s a version that runs them all in parallel, and then once the promises are all resolved, it finds the first that yielded a truthy value.

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement