繁体   English   中英

尝试将两个 rest api 端点合并并加载在一起

[英]Trying to merge and load two rest api endpoints together

I was trying to get data from merge together to Rest API endpoints the first endpoint https://spaceshare.com/api/data/places should return a list of places with an ID and the Image URL is https://spaceshare.com /api/data/img/{placeId} placeId 与第一个端点返回的Id相同

import {data} from './data.js';


/* @typedef{{
 *   id: string,
 *   name: string,
 *   address: string,
 *   stars: number,
 *   reviews: number,
 *   price: string,
 *   description: string,
 *   img?: string,
 /* }}
 

export async function initializePlaces() {
  const placesWithImages = await loadPlacesWithImages();
  data.set('places', placesWithImages);
  data.set('placesLoaded', true);
}

这是我尝试渲染从第二个端点返回的 img

async function loadPlacesWithImages() {
  const getImage = (placeId) => {
  fetch(`https://spaceshare.com/api/data/img/${placeId}`)
  .then((response) => response.json())
  .then((data) => {
    let image = data.img;
    return image;
  });
  return fetch("https://spaceshare.com/api/data/places")
  .then((response) => response.json())
  .then((data) =>
    data.places.map((element) => ({
      id: element.id,
      name: element.name,
      address: element.address,
      stars: element.stars,
      reviews: element.reviews,
      price: element.price,
      description: element.description,
      img: getImage(element.id),
  }))
  );

  };

} 

我如何能够在 map function 中同时返回来自两个端点的信息?

您需要将 map 的返回值存储在一个变量中。 该变量将包含等待解析的 Promise 对象数组。 使用Promise.all(variableName) 这将返回您构造的对象数组。

而不是返回fetch() ,而是return Promise.all(variableName)

参考

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM