Skip to content

Instantly share code, notes, and snippets.

@bayleedev
Last active February 23, 2017 18:17
Show Gist options
  • Save bayleedev/601b410875c5ad03f41d367b89f661bf to your computer and use it in GitHub Desktop.
Save bayleedev/601b410875c5ad03f41d367b89f661bf to your computer and use it in GitHub Desktop.
const urls = [
'https://google.com',
'http://blainesch.com',
'https://github.com',
]
let follower = Promise.resolve()
for (let currentUrl of urls) {
follower = follower.then(() => {
return new Promise((resolve) => {
console.log('processing', currentUrl)
setTimeout(resolve, 1000)
})
})
}
const urls = [
'https://google.com',
'http://blainesch.com',
'https://github.com',
]
const process = (urls) => {
const currentUrl = urls.shift()
return new Promise((resolve) => {
console.log('processing', currentUrl)
setTimeout(resolve, 1000)
}).then(() => {
if (urls.length > 0) {
return process(urls)
}
})
}
process(urls.slice(0)).then(() => {
console.log('done')
})
@keighty
Copy link

keighty commented Jan 25, 2017

oooh.. I like the the top loop! it is super concise, and it seems like the recursive one uses the same mechanism, and is destructive to the URL array, which we might want to reuse over and over. Which one do you like best?

@afaur
Copy link

afaur commented Jan 28, 2017

let foo = Promise.resolve()

const urls = [
  'https://google.com',
  'http://blainesch.com',
  'https://github.com',
]

let timeout = (time) => {
  return new Promise((resolve) => {
    setTimeout(resolve, time)
  })
}

for (let url of urls) {
  foo = foo.then(() => {
    console.log(url)
    return timeout(1000)
  })
}

Abstracted timeout to a function.

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