[英]How to fetch an API inside a map function?
I want to fetch an API inside a map function.我想在 map function 中获取 API。 How can I do it?
我该怎么做? Inside an ul html element, I need to fetch another API.
在 ul html 元素中,我需要获取另一个 API。 That API looks like "$(url)/cities/${state}".
API 看起来像“$(url)/cities/${state}”。 It will give me a list of city that I want to render with another map function.
它会给我一个我想用另一个 map function 渲染的城市列表。 I tried to do a way but it returned "[object Promise]"
我试图做一个方法,但它返回“[object Promise]”
fetch(`${url}/states/${Country}`)
.then((response) => {
return response.json();
})
.then((data) => {
const States = data.states.map(({ state }) => {
return `<div class="col-6 col-sm-3 p-2">
<p class="state" id="stateID">${state}</p>
<ul class="city-list">
/*I want a city list here by fetching another API accroding to this ${state}*/
${fetch(`${url}/cities/${state}`)
.then((response) => {
return response.json();
})
.then((data) => {
data.cities.map((citys) => {
return `<li class="city"><a href="#">${citys}</a></li>`;
})
.join("");
document.querySelector(".city-list").insertAdjacentHTML("beforeend", City);
})}
/*But this fetch function return [object Promise]*/
</ul>
</div>`;
})
.join("");
document.querySelector(".line")
.insertAdjacentHTML("afterend", States);
Here is a clean way to do what you want to do.这是一种干净的方式来做你想做的事。 It includes
fetch
api inside map
它包括在 map 内
fetch
map
import { pipe, fork, map } from 'https://deno.land/x/rubico/rubico.js'
const identity = x => x
const join = delim => x => x.join(delim)
const template = ({ state, cities }) => `
<div class="col-6 col-sm-3 p-2">
<p class="state" id="stateID">${state}</p>
<ul class="city-list">${cities}</ul>
</div>`
const fetchJSON = url => fetch(url).then(res => res.json())
const citiesHTML = pipe([
({ state }) => `${url}/cities/${state}`,
fetchJSON,
({ cities }) => cities,
map(city => `<li class="city"><a href="#">${city}</a></li>`),
cities => {
for (const city of cities) {
document.querySelector(".city-list").insertAdjacentHTML("beforeend", city)
}
return cities
}
join(''),
])
pipe([
fetchJSON,
({ states }) => states,
map(pipe([
fork({
state: identity,
cities: map(citiesHTML),
}),
template,
])),
join(''),
statesHTML => {
document.querySelector(".line").insertAdjacentHTML("afterend", statesHTML)
},
])(`${url}/states/${Country}`)
I wrote the library in the example to solve complex async tasks like yours.我在示例中编写了库来解决像您这样的复杂异步任务。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.