簡體   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