我使用flickr API搜索图像,我想同时用他们的标签拍照。
要做到这一点,我首先需要使用flickr.photos.search方法来获取photo_id并构建照片网址(第一个和第二个'然后'方法)。在第3个'then'部分,我使用另一个API方法flickr.photos.getInfo来获取每张照片的标签,最后返回urlPhoto和tagsInfo,如json。
问题是tagsInfo变量继续是一个承诺,我无法渲染照片的标签(数组)。但是,urlPhoto具有正确的值。
export function fetchAll(...) {
return fetch(BASE_URL + encodeGetParams(params1), options)
.then(response => {
return response.json();
})
.then((data) => {
return data.photos.photo.map(e =>
({
"photo_id": e.id,
"urlPhoto": 'https://farm'+e.farm+'.staticflickr.com/'+e.server+'/'+e.id+'_'+e.secret+'.jpg',
})
)
})
.then((data) => {
return data.map(e => {
const url = BASE_URL + encodeGetParams({ ...params2, "photo_id": e.photo_id });
const tagsInfo = fetch(url, options)
.then(data => data.json())
.then(data => data.photo.tags.tag.map(e => e._content));
return {
"urlPhoto": e.urlPhoto,
"tagsInfo": tagsInfo
}
}
)
})
}
你可以为数组中的每个元素创建一个单独的promise,在这些promises上使用Promise.all
并返回它。
export function fetchAll(/* ... */) {
return fetch(BASE_URL + encodeGetParams(params1), options)
.then(res => res.json())
.then(data => {
const promises = data.photos.photo.map(e => {
const result = {
urlPhoto: `https://farm${e.farm}.staticflickr.com/${e.server}/${e.id}_${e.secret}.jpg`
};
const url = BASE_URL + encodeGetParams({ ...params2, photo_id: e.photo_id });
return fetch(url, options)
.then(res => res.json())
.then(data => {
result.tagsInfo = data.photo.tags.tag.map(e => e._content);
return result;
});
});
return Promise.all(promises);
});
}
你是不是只需要返回最后一次获取并添加一个可以解决的额外.then
{
"urlPhoto": e.urlPhoto,
"tagsInfo": tagsInfo
}
喜欢
export function fetchAll(...) {
return fetch(BASE_URL + encodeGetParams(params1), options)
.then(response => {
return response.json();
})
.then((data) => {
return data.photos.photo.map(e =>
({
"photo_id": e.id,
"urlPhoto": 'https://farm'+e.farm+'.staticflickr.com/'+e.server+'/'+e.id+'_'+e.secret+'.jpg',
})
)
})
.then((data) => {
return data.map(e => {
const url = BASE_URL + encodeGetParams({ ...params2, "photo_id": e.photo_id });
return fetch(url, options)
.then(data => data.json())
.then(data => data.photo.tags.tag.map(e => e._content))
.then(tagInfo => {
return {
"urlPhoto": e.urlPhoto
"tagsInfo": tagsInfo
}
})
}
)
})
}
你目前正在做的是在tagsInfo fetch promise解决之前返回urlPhoto / tagsInfo,这样就可以修复它!