I'm working on a function that uses Array.reduce, and I need to add an asynchronous API call inside the reduce function. This requires me to use an async function for the callback I pass into reduce
, since I'm using await
inside the function to wait for the asynchronous API call.
I'm having some trouble writing the reduce correctly. Here's how it currently is (working):
const result = records.reduce((array, currValue) => {
//do stuff
return array
}, [])
Here's what I tried to change it to:
const result = records.reduce(async(array, currentValue) => {
// do stuff
someValue = await asyncCall(currentValue)
array.add(someValue)
return array
}, [])
The error I'm getting is 'No overload matches this call'.
This seems to make sense to me, since reduce takes in a callback that returns an array, and async functions return a callback, not an array. But when I read other examples of how to pass async functions into .reduce, they all seem to just pass an async function into reduce with no problem.
Here are a few links I looked at:
https://advancedweb.hu/how-to-use-async-functions-with-array-reduce-in-javascript/
JavaScript array .reduce with async/await
https://gyandeeps.com/array-reduce-async-await/
The moment I declare the reduction function into async, I get the no matching overloads error, which makes sense to me. I'm not sure how this seems to work for other people.