【问题标题】:Problem get data from an array using fetch API [duplicate]使用 fetch API 从数组中获取数据的问题 [重复]
【发布时间】:2020-06-29 15:26:15
【问题描述】:

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

    您正在使用 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);
    });
    

    【讨论】:

      【解决方案2】:

      这里的问题是,当您打印值时,还没有进行获取。尝试这样做:

      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]);
          });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-22
        • 2020-11-16
        • 1970-01-01
        相关资源
        最近更新 更多