· 3 min read
If you've ever tried using
async / await
, you've likely stumbled into errors such as
array.push() is not a function
. Fear not! We will walk through a simple example to get you on your way.
cannot read .push() of undefined
In the above example, our function will loop through each of the three locations, make an API call for job posting data, and add the data and location to an array. If you were to run this function, you'd receive the error
. Why is that? The culprit is with our accumulator. If you add a
jobsAccumulator.push is not a function
message at the top of the reducer, you'll see during the second iteration that
is an unresolved promise.
To fix this, we need to do two things:
The first change to take a look at above is on line 12. We're setting our accumulator as a resolved promise that contains an array. We're doing this so that we can resolve our previous promises before continuing on to the next.
The other key piece is on line 5. We've renamed our accumulator to
so that we can get a better idea of what's happening behind the scenes. Before continuing through each iteration, we're waiting on the previous promise to resolve and then we fetch the next set of job postings.
And it's as simple as that! After the reduce method has finished, our function
should return a nicely formatted array of job postings for each location.
You can play around with the Code Pen here.
Stack Five is a React and NodeJS consulting company that strives to push the boundaries of the web and build meaningful things. If you're looking to create a cutting-edge web application or need software engineering resources for your project, please contact us.