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 is the same as the Id returned from the first endpoint
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);
}
This is my attempt to render the img returned from the second endpoint
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),
}))
);
};
}
How would I be able to return the information from both endpoints together in the map function?
You'll need to store the return from the map in a variable. That variable will contain an array of Promise objects that are waiting to resolve. Use Promise.all(variableName)
. That will return an array of objects you've constructed.
Instead of returning fetch()
, return Promise.all(variableName)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.