Home > Software design >  stored array outside of async function in nodejs fetch
stored array outside of async function in nodejs fetch

Time:11-11

How do I get the value of the failed array outside of the function? Because I need this array as an input for other functions.

failed = [];
async function fetchFromApi(i) {

    var ApiEndpoint = "https://jsonplaceholder.typicode.com/todos/"   i
    var httpRequest = {
        method: "GET"
    }


    var response = await fetch(ApiEndpoint, httpRequest);
    if (!response.ok) { // Necessary for error handling, fetch does not return an error if HTTP request fails

        failed.push(i);
        console.log(failed)

    } else {
        let symbolData = await response.json();

        console.log(JSON.stringify(symbolData))
        return JSON.stringify(symbolData);
    }

};
    
fetchFromApi("abc")
console.log(failed)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

The console.log("failed") in the code above gives me an empty array []. I want it to be getting ["abc"] when this variable being called outside of the function

UPDATE EDIT (new follow-up question):

I tried @SlothOverlord 's solution and it seems to work below is the example.

const myFunction = async (j) => {  
  failed = [];
  async function fetchFromApi(i) {

      var ApiEndpoint = "https://jsonplaceholder.typicode.com/todos/"   i
      var httpRequest = {
          method: "GET"
      }


      var response = await fetch(ApiEndpoint, httpRequest);
      if (!response.ok) { // Necessary for error handling, fetch does not return an error if HTTP request fails

          failed.push(i);

      } else {
          let symbolData = await response.json();

          console.log(JSON.stringify(symbolData))
          return JSON.stringify(symbolData);
      }

  };
 
  await fetchFromApi(j)
  return failed
}

myFunction("abc").then(data=>console.log(failed))
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

However, when I add in a forEach statement within the function, it breaks and returns an empty array again. See example below. What's going on here?

const myFunction = async (j) => {  
  failed = [];
  async function fetchFromApi(arrays) {

    arrays.forEach(async function(i) {


    var ApiEndpoint = "https://jsonplaceholder.typicode.com/todos/"   i
    var httpRequest = {
      method: "GET"
    }


    var response = await fetch(ApiEndpoint, httpRequest);
    if (!response.ok) { // Necessary for error handling, fetch does not return an error if HTTP request fails

      failed.push(i);
      // console.log(failed)

    } else {
      let symbolData = await response.json();

      console.log(JSON.stringify(symbolData))
      return JSON.stringify(symbolData);
    }
    
    });
 

}
  await fetchFromApi(j)
  // console.log(failed)
  return failed
}

myFunction(["aaa", "abc"]).then(data=>console.log(failed))
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You need to await the fetchFromApi("abc") function.

Async await only works INSIDE the function, not outside of it.

So what happened is:

fetchFromApi("abc") is called
console.log(failed) is empty
fetchFromApi("abc") finished

The solution is to wrap the function in async and await the fetchFromApi call

const myFunction = async () => {
//...

failed = [];
async function fetchFromApi(i) {
//...
}


await fetchFromApi("abc")
console.log(failed)
}

CodePudding user response:

fetchFromApi is an async method, you need to await it if you want to see it's result logged.

JavaScript has a concurrency model based on an event loop, which is responsible for executing the code, collecting and processing events. when the async call will have it's result it will be placed in the callback queue and on the next iteration (tick), it will be popped out from there and placed in the execution stack to be processed. when you use await, the exection call will be halted at that point and will progress until the async call has it's result.

failed = [];
async function fetchFromApi(i) {

    var ApiEndpoint = "https://jsonplaceholder.typicode.com/todos/"   i
    var httpRequest = {
        method: "GET"
    }


    var response = await fetch(ApiEndpoint, httpRequest);
    if (!response.ok) { // Necessary for error handling, fetch does not return an error if HTTP request fails

        failed.push(i);
        console.log(failed)

    } else {
        let symbolData = await response.json();

        console.log(JSON.stringify(symbolData))
        return JSON.stringify(symbolData);
    }

};
    
await fetchFromApi("abc")
console.log(failed)
<iframe name="sif4" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

JS event loop - https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop

  • Related