Search code examples
javascriptloopsasync-awaitfetch-api

.push() does not work under throw, using async await method to fetch data in a loop in javascript


I'm trying to fetch data one by one in order using async await and push the response.json to a array. However, the code I use below does not display the result in console.log(b);. Any one know what's the issue?

Thank you in advance!

async function fetch_data(){

    let b = [];
    
    for (let i = 1; i < 10; i++) {

        let response = await fetch('https://SOME_URL/' + i, {
          method: "GET",
          headers: {"Key": "123456"}})


        if (!response.ok) {
        var error_detail = `An error has occured: ${response.status}`;
        throw new Error(error_detail);
        }

        var data = await response.json();

        // await b.push(data);
        b.push(data);
    }

    // await Promise.all(b).then(function (b) {
    //         console.log(b)})

    console.log(b);
    return b;

}

When I run the script, it does not return anything in the console

fetch_data().catch(error => {
  error.error_detail;
});

UPDATE: seems solved using my answer below. not sure why though.

The issue in which console.log(b); not displaying the output is because for example 'https://SOME_URL/' + i as i increases, IF when i = 5 and it returns error, then the console.log(b); will not return anything. If I set the i < 5, then console.log(b); will return the output b. So which means if any fetch in the loop returns error within the limit of i, then the push will not work (b will be empty) and hence console.log(b); will not return anything.

Anyone have idea how to solve this?


Solution

  • I updated several places One of the issues would be the function name: "fetch" as same as the default fetch function name.

    const fetchData = async(symbol) => {
      try {
        let promiseGroup = [];
    
        const subFetch = async(i) => {
          const BASE_URL = `https://reqres.in/api/products`
          return fetch(`${BASE_URL}/${i}`, {
            method: "GET",
            headers: {
              "Key": "123456"
            }
          }).then(res => res.json())
        }
    
        for (let i = 1; i < 10; i++) {
          promiseGroup.push(i);
        }   
        const results = await Promise.all(promiseGroup.map(subFetch))
        console.log(results)
        return result;
    
      } catch (error) {
        const error_detail = `An error has occured: ${error}`;
        throw new Error(error_detail);
      }
    }
    console.log(fetchData())