2

I'm trying to create a bookmarklet that tracks all the links on a page, check how the server responds and return the http requests.

The problem I'm encountering is that I'm not achieving get data from array. This is my code:

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 ¿?¿?

Does anyone know how I can access to the data in the array? I don't know what else I can do ...

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122

2 Answers2

3

You are working with promises (fetch) which means that you must wait that all the promises are resolved before checking the results.

To make it possible, you can use Promise.all that will run all the promises in parallel and wait for their results.

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);
});
Weedoze
  • 13,683
  • 1
  • 33
  • 63
0

The problem here, is when you are printing the values, the fetch didn't happened yet. Try do like this:

const tags = document.getElementsByTagName('a'); 
let code = [];

const promises = Array.from(tags).map(tag => fetch(tag));
Promise.all(promises)
    .then(results => {
        code = results.map(x => x.status);
        console.log('Status Codes: ', code);
        console.log('First status code: ', code[0]);
    });
Kevyn Klava
  • 316
  • 1
  • 7