嵌套 fetch/then 方法

Nested fetch/then methods

我正在使用 flickr API 搜索图片,我想同时获取带有他们标签的照片。

为此,我首先需要使用 flickr.photos.search 方法来获取 photo_id 并构建照片 url(第 1 和第二种 'then' 方法)。在第 3 'then' 部分,我使用了另一个 API 方法 flickr.photos.getInfo 来获取每张照片的标签,最后 return url照片和标签信息,例如 json.

问题是 tagsInfo 变量仍然是一个承诺,我无法呈现照片的标签(数组)。但是,url照片具有正确的值。

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       
        }
      }
      )
    })
}

您是否不仅需要 return 最后一次提取并添加一个额外的 .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       
          }
        })
      }
      )
    })
}

您目前正在做的是 return 在 tagsInfo 提取承诺解决之前 urlPhoto/tagsInfo,所以额外的应该会修复它!

您可以为数组中的每个元素创建一个单独的承诺,对这些承诺使用 Promise.all 并 return 那。

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);
    });
}