gpt4 book ai didi

javascript - Fetch 不存储数组 for 循环之后的值 - Javascript

转载 作者:行者123 更新时间:2023-12-03 01:11:52 26 4
gpt4 key购买 nike

我想向从 Wikimedia API 获取的位置数组中的每个对象添加一个描述属性,但是当我在循环内记录其值时,它就在那里,但在循环外,它会被删除。

我寻找带有 async/await 函数或 Promise.all() 的解决方案,但没有成功。

有没有办法正确存储该值以便稍后访问?

let locations = [
{
latLng: [33.975561111111,28.555830555556],
name: 'Saint Catherine\'s Monastery',
searchTerm: 'Saint Catherine\'s Monastery',
urlSerchTerm: 'Saint%20Catherine\'s%20Monastery'
},
{
latLng: [29.91667,31.2],
name: 'Bibliotheca Alexandrina',
searchTerm: 'Bibliotheca Alexandrina',
urlSerchTerm: 'Bibliotheca%20Alexandrina'
}
];

async function fetchAsync (site, location) {
// await response of fetch call
let response = await fetch(site);
// only proceed once promise is resolved
let data = await response.json();
// only proceed once second promise is resolved
location.description = data[2][0];

return location.description;
}

// let fetches = [];
for (let i = 0; i < locations.length; i++) {
let site = `https://en.wikipedia.org/w/api.php?action=opensearch&search=${locations[i].urlSerchTerm}&limit=1&namespace=0&format=json&origin=*`;

fetchAsync(site, locations[i])

}
console.log(locations[1].description)

最佳答案

这只是一个时间问题。当代码片段最后一行中的 console.log(...) 语句正在执行时,您的 fetch 调用将异步执行同步。换句话说,对 fetch 发出的请求的响应将在 console.log(...) 之后返回,并且 description 属性将在仍然是未定义的。

您可以通过查看下面的代码来说服自己这一点,其中 console.log(...) 语句包含在超时中。现在,将记录获取的描述,而不是未定义

let locations = [
{
latLng: [33.975561111111,28.555830555556],
name: 'Saint Catherine\'s Monastery',
searchTerm: 'Saint Catherine\'s Monastery',
urlSerchTerm: 'Saint%20Catherine\'s%20Monastery'
},
{
latLng: [29.91667,31.2],
name: 'Bibliotheca Alexandrina',
searchTerm: 'Bibliotheca Alexandrina',
urlSerchTerm: 'Bibliotheca%20Alexandrina'
}
];

async function fetchAsync (site, location) {
// await response of fetch call
let response = await fetch(site);
// only proceed once promise is resolved
let data = await response.json();
// only proceed once second promise is resolved
location.description = data[2][0];

return location.description;
}

// let fetches = [];
for (let i = 0; i < locations.length; i++) {
let site = `https://en.wikipedia.org/w/api.php?action=opensearch&search=${locations[i].urlSerchTerm}&limit=1&namespace=0&format=json&origin=*`;

fetchAsync(site, locations[i])

}

window.setTimeout(() => {console.log(locations);}, 5000);

您可以按照 @JeremyThille 的建议使用 Promise.all 解决此问题。这个SO answer解释了 Promise.all 的第二种用法,以防令人困惑。

let locations = [
{
latLng: [33.975561111111,28.555830555556],
name: 'Saint Catherine\'s Monastery',
searchTerm: 'Saint Catherine\'s Monastery',
urlSerchTerm: 'Saint%20Catherine\'s%20Monastery'
},
{
latLng: [29.91667,31.2],
name: 'Bibliotheca Alexandrina',
searchTerm: 'Bibliotheca Alexandrina',
urlSerchTerm: 'Bibliotheca%20Alexandrina'
}
];


const fetchDescription = (location) => fetch(`https://en.wikipedia.org/w/api.php?action=opensearch&search=${location.urlSerchTerm}&limit=1&namespace=0&format=json&origin=*`);

const descriptionRequests = locations.map(fetchDescription);
Promise.all(descriptionRequests)
.then(responses => Promise.all(responses.map(r => r.json())))
.then(descriptions => {
descriptions.forEach((description, index) => { locations[index].description = description[2][0]; });
})
.then(() => {
console.log(locations);
});

关于javascript - Fetch 不存储数组 for 循环之后的值 - Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52183741/

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