[英]trying to solve practice problem — unable to set data from my fetch request though it shows up in console.log
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);
}
我正在研究這個 function 來設置變量 id、name 等。它在控制台中有效,但在我嘗試返回時無效。 我嘗試了forEach
並返回 - 它沒有用。 我覺得在語法上我搞砸了。 請幫幫我,謝謝!
function loadPlacesWithImages() {
fetch('https://byteboard.dev/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 }))}
您必須返回獲取 function。 在第一段代碼中,您沒有正確關閉評論。
在你的情況下 loadPlacesWithImages 什么都不返回。 和您的 function 初始化變量 id、name 等...可能您想要獲取對象數組,在這種情況下您應該執行類似的操作
/**
* @returns Promise<Array<SomeObject>>
*/
function loadPlacesWithImages() {
fetch('https://byteboard.dev/api/data/places')
.then(response => response.json())
.then(data => data.places.map(element => ({ // add missing '(' there
id : element.id,
name : element.name,
address: element.address,
stars: element.stars,
reviews: element.reviews,
price: element.price,
description: element.description })))} // add missing ')' there
為避免此類錯誤,您可以
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.