I'm experiencing some weird behavior when using promises inside of a map.
This isn't really a problem per se, but I'd like to understand what's going on.
let books = [
{Name: "Moby Dick",
AuthorId: 1
},
{Name: "The Great Gatsby",
AuthorId: 2}
]
let authors = [
{AuthorId: 1,
Name: "Herman Melville"
},
{AuthorId: 2,
Name: "F. Scott Fitzgerald"
}
]
const getAuthorName = (AuthorId) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(authors.find((author) => {
return author.AuthorId === AuthorId
}).Name)
}, 1000
})
}
let responseArray = []
let promises = books.map((book) => (
getAuthorName(book.AuthorId).then((res) => {
responseArray.push({
...book,
AuthorName: res
})
})
))
setTimeout(() => console.log(responseArray), 500)
//I would expect to have to do this:
//Promise.all(promises).then((res) => console.log(res))
I would expect the
setTimeout(() => console.log(responseArray), 5000)
to log an empty string, because the array of promises hasn't been run through Promise.all yet, but it seems like even though the map should just be returning an array of promises, it's actually running the promises. Why is this?
Edit
I've edited the getAuthor promise to wait a second before resolving to further elaborate because that wasn't the point I was trying to get at.
I would expect mapping over an array, to return a new array with whatever is returned in the map. For example, if I do
let arrayOfPromises = books.map((book) => {
return getAuthor(book.AuthorId)
}
I would expect arrayOfPromises to be an array of getAuthor promises.
However, when I throw a .then() on the end of the promise that is being returned, it appears that the code in the .then() is evaluating.
So if I do
let promises = books.map((book) => {
return getAuthor(book.AuthorId).then((res) => {
console.log(res)
})
}
In the console I'll see "Herman Merville" and "F. Scott Fitzgerald" and in the promises var I'll have an array of promises.
While I thought that each getAuthor's .then would only evaluate once I call Promise.all(promises) because the getAutor promise being returned inside the map. Am I understanding something wrong here?
Promise.resolve(5)and that's a promise for the value 5. It has already "run".