Skip to content

Instantly share code, notes, and snippets.

@DavidWells
Forked from atinux/async-foreach.js
Created October 22, 2018 04:10
Show Gist options
  • Save DavidWells/a0819be9f4041351a704bfc8360f6335 to your computer and use it in GitHub Desktop.
Save DavidWells/a0819be9f4041351a704bfc8360f6335 to your computer and use it in GitHub Desktop.
JavaScript: async/await with forEach()
const waitFor = (ms) => new Promise(r => setTimeout(r, ms))
const asyncForEach = (array, callback) => {
for (let index = 0; index < array.length; index++) {
await callback(array[index], index, array)
}
}
const start = async () => {
await asyncForEach([1, 2, 3], async (num) => {
await waitFor(50)
console.log(num)
})
console.log('Done')
}
start()
@DavidWells
Copy link
Author

export const fetchData = searchTerm => {
  const url = `${ROOT_URL}?s=${searchTerm}${API_KEY}`;
  return dispatch => {
    dispatch(fetchStarted());
    axios
      .get(url)
      .then(
        response => Object.keys(mapKeys(response.data.Search, 'imdbID')),
        dispatch(fetchMainData())
      )
      .then(async movieIDs => {
        let fullDetailArray = [];
        await asyncForEach(movieIDs, async imdbID => {
          const url = `${ROOT_URL}?i=${imdbID}${API_KEY}`;
          await axios.get(url).then(response => {
            fullDetailArray.push(response.data);
          });
        });
        console.log('DETAIL ARRAY', fullDetailArray);
        dispatch(fetchMainDataSuccess(fullDetailArray));
      });
  };
};

@DavidWells
Copy link
Author

DavidWells commented Oct 22, 2018

const waitFor = (ms) => new Promise(r => setTimeout(r, ms))

async function asyncForEach(array, callback) {
  for (let index = 0; index < array.length; index++) {
    await callback(array[index], index, array)
  }
}

const start = async () => {
  await asyncForEach([1, 2, 3], async (num) => {
    await waitFor(50)
    console.log(num)
  })
  console.log('Done')
}
start()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment