amslezak
12/8/2018 - 3:02 AM

simple for-await-of snippet/example

simple for-await-of snippet/example

// for await of
const fetch = require('node-fetch')

const urls = [
  'https://swapi.co/api/people/1',
  'https://swapi.co/api/people/2',
  'https://swapi.co/api/people/3',
  'https://swapi.co/api/people/4',
]

// sync
const loopThroughUrls = url => {
  for (url of urls) {
    console.log(url)
  }
}

// async
const getData = async function() {
  const arrayOfPromises = urls.map(url => fetch(url))
  for await (let request of arrayOfPromises) {
    const data = await request.json()
    console.log(data)
  }
}