[Vuejs]-Using variable from a Async function

1👍

You shouldn’t be doing a forEach with async. You should use map and get each promise out. Then do Promise.all. Something like this:

async function statusCheck (items) {
    let promises = items.map(item => {
      let url = "https://somelink" + item.split(' ')[0] + "/54x54/";
      return fetchResponse(url);
    });

    await Promise.all(promises);

    // figure out which ones to return.
  }

1👍

Async functions need to return a Promise. Your code runs synchronously. I am not sure why the browser won’t tell you. So your statusCheck() function needs to return a Promise object to be awaitable. This also applies to the the forEach loop in the statusCheck. And I think that you cant do the foreach async because the native function wont wait for those callbacks.
See this reference for async function: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Statements/async_function

1👍

There is no reason to use setTimeout. the main problem is that you are using await inside the function you are passing to forEach, and there is no reason for javascript to wait until all of the requests resolve and then returning the array. it keeps going and returns possibly an empty array first. and when you are using the new created array it, some of the requests might resolve and they results will be pushed to that array. you can use this instead:

async function statusCheck (items) {
  return Promise.all(items.map(async (item) => {
    let url = "https://somelink" + item.split(' ')[0] + "/54x54/"
    let status = await fetchResponse(URL)
    if(status !== 200) {
      return;
    }
    return item;
  }).filter(Boolean);
}  

I used Boolean just to remove items that checking them by API might result in a status other than 200. in this case the function return;s or in the other words, returns undefined. as a matter of fact, I’ve filtered those results by filter(Boolean)

Leave a comment