【发布时间】:2020-07-13 01:11:42
【问题描述】:
我有一个 nodejs 应用程序,它从不同的 api 获取数据,我想聚合来自不同 api 的数据,然后将其发送出去。但是我只能解决 api 数据获取的承诺,但 res.send 只发送空数组。我猜 res.send 没有等待 json() 函数解析并且已经发送了数据。我该如何解决这个问题?
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)
})
})
【问题讨论】:
-
Promise.all(/* your promises */).then(/* your handling of those*/).then(data => res.send(data)) -
你已经完成了
Promise.all(...).then(...)一次。您需要为每组承诺这样做。 -
@VLAZ 我尝试了你的 double then 方法,但没有成功
-
@miketsui3a 你
return data了吗? -
@VLAZ 你的意思是 ```Promise.all([x,y]).then(files=>{......return data}) 吗?
标签: javascript node.js express asynchronous promise