I have a nodejs app which fetch data from different api and I want to aggregate the data from different api and then send it out. However I can only resolve the promise of api data fetching but the res.send only sending empty array. I am guessing the res.send didn't wait for the json() function to resolve and already sent out the data. How can I resolve this problem?
app.get('/:keyword',(req,res)=>{
let unsplashPromise = unsplash.search.photos(......)
let pixabayPromise = fetch(......)
let jsonPromise
let data = []
Promise.all([unsplashPromise, pixabayPromise]).then(files=>{
files.map((promise)=>{
if(promise.url.includes("unsplash")){
promise.json().then((photos)=>{
photos.results.map((photo)=>{
data.push({
image_ID: photo.id,
thumbnails: photo.urls.thumb,
preview: photo.urls.regular,
title: photo.alt_description,
source: "unsplash",
tags: photo.tags
})
})
})
}else if(promise.url.includes("pixabay")){
promise.json().then((json)=>{
json.hits.map((photo)=>{
data.push({
image_ID: photo.id,
thumbnails: photo.previewURL,
preview: photo.largeImageURL,
title: null,
source: "pixabay",
tags: photo.tags
})
})
})
}
return data
})
}).then(()=>{
res.send(data)
})
})