I am having some trouble finding a way to get this to work. Basically I get a list of users from a mock api endpoint and what I want to do is actually map each user to only have an email.
// returns 10 users from mock api so we have something to work with
function getUsers() {
return fetch('https://jsonplaceholder.typicode.com/users')
.then(res => res.json())
.then(data => {
console.log(data)
return data
})
}
// this just gives us something to map over
const usersList = getUsers()
// get specific user by id e.g. /users/1
const mappedUsers = (users) => {
return users.map(async user => {
// get a specific user by id
const response = await fetch(`https://jsonplaceholder.typicode.com/users/${user.id}`)
const userData = await response.json()
// and only return the email property from the api reponse for each user
return {
userEmail: userData.email
}
})
}
mappedUsers(usersList)
The end result should just look like this:
mappedUsers = [
{ userEmail: 'name of the first email from api' },
{ userEmail: '...' },
...
]
userListwill be a promise, not an array. You have to hook into the settlement of the promise and then use the fulfillment value. Similarly,mappedUserswill be an array of promises, so you have to wait for the promises to settle (usually by usingPromise.all) and then access their fulfillment values. See the answers to the linked questions for details.fetchAPI I describe here (my anemic old blog).fetchonly rejects its promise on network errors, not HTTP errors. You have to check for HTTP errors on purpose (by checkingokon the response before reading the response body).mapdoes its work synchronously. When you call anasyncfunction, it's synchronous up until the firstawait,return, orthrow; at that point, the function returns a promise. Somapsynchronously starts eachfetchand builds an array of the promises, allowing the network operations to run in parallel.