我正在尝试创建一个书签来跟踪页面上的所有链接,检查服务器如何响应并返回 http 请求。
我遇到的问题是我没有实现从数组获取数据。 这是我的代码:
let a = document.getElementsByTagName('a');
let code = [];
for(let i=0; i<a.length; i++) {
let myRequest = a[i].href;
let x = fetch(myRequest).then(function(response) {
return response.status;
})
x.then(function(result) {
code.push((result));
})
}
console.log(code); // [200, 200, ....]
console.log(Array.isArray(code)); // true
let codeOne = code[0];
console.log(codeOne); // undefined ¿?¿?
有谁知道如何访问数组中的数据? 我不知道我还能做什么...
最佳答案
您正在使用 promise (fetch
),这意味着您必须等待所有 promise 都得到解决,然后才能检查结果。
为了使其成为可能,您可以使用 Promise.all
来并行运行所有 Promise 并等待其结果。
let a = document.getElementsByTagName('a');
//Create the array of promises
const linkPromises = a.map(aTag => fetch(aTag.href).then(response => response.status));
//Run the promises in parallel
Promise.all(linkPromises).then(results => {
//All promises are resolved
console.log(results); // [200,200,...]
}).catch(error => {
console.log("An error occurs " + error);
});
关于javascript - 使用 fetch API 从数组获取数据时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60741170/