gpt4 book ai didi

javascript - 使用数组和 for 循环获取

转载 作者:行者123 更新时间:2023-11-30 14:17:33 25 4
gpt4 key购买 nike

我需要获取大约五个 URL(api)。我用网址制作了一个数组。我需要做一个 for 循环,这样我就可以将每个 url-info 放入不同的框中。我早些时候从获取 url 开始,然后我在页面上写下了我想在页面上输出的每件事的 +info.name+ 等,但这需要很长时间,所以我需要使用 for 循环。我怎么做?所以我不必多次获取和写入 +info+?

var urls = ["url i need to fetch",
"url i need to fetch",
"url i need to fetch",];

var url = "url i wanted to fetch";

fetch (url)
.then (result => result.json())
.then ((res) => {
console.log(res);
createCards (res);

})
.catch(err => console.log(err))

function createCards(card) {
var div = document.getElementById('card');



div.innerHTML = `


<h2>`+card.name+`</h2>
<div>
<b>HTML text </b>`+info.from.card+`</div>

最佳答案

您可以使用 Promise.all() 同时运行所有请求:

const urls = [
"url i need to fetch",
"url i need to fetch",
"url i need to fetch"
];
Promise
.all( urls.map( url => fetch( url)))
.then( responses => responses.map( response => response.json()))
.then( results => {
// do something with the results array
})
.catch( error => {
// handle the error
});

关于javascript - 使用数组和 for 循环获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53322611/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com