问题从数组获取数据-提取api-Javascript

问题描述 投票:0回答:1

我正在尝试创建一个跟踪页面上所有链接的书签,检查服务器的响应方式并返回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 ¿?¿?

有人知道我如何访问数组中的数据吗?我不知道我还能做什么...

提前感谢

javascript arrays promise fetch fetch-api
1个回答
0
投票

您正在处理承诺(fetch),这意味着您必须等待所有承诺都得到解决,然后才能检查结果。

为了使其成为可能,您可以使用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);
});
© www.soinside.com 2019 - 2024. All rights reserved.