Skip to content

Instantly share code, notes, and snippets.

@sgb-io
Created October 9, 2017 15:04
Show Gist options
  • Select an option

  • Save sgb-io/6b33e1b162b5f7ba9801447e430213e8 to your computer and use it in GitHub Desktop.

Select an option

Save sgb-io/6b33e1b162b5f7ba9801447e430213e8 to your computer and use it in GitHub Desktop.
Example usage of async functions (ES7)
function foo(delay) {
return new Promise(resolve => {
setTimeout(() => {
resolve(Math.random())
}, delay)
})
}
async function run(delaySeconds) {
const a = foo(delaySeconds * 1000)
const b = foo(delaySeconds * 1000)
const c = foo(delaySeconds * 1000)
// Waits for 3 calls in parallel
return {
a: await a,
b: await b,
c: await c
}
}
console.log('starting!')
run(0.5).then((values) => {
console.log('0.5 seconds')
console.log(values)
})
run(1).then((values) => {
console.log('1 second')
console.log(values)
})
run(3).then((values) => {
console.log('3.5 seconds')
console.log(values)
})
run(5).then((values) => {
console.log('5 seconds')
console.log(values)
})
@sgb-io
Copy link
Author

sgb-io commented Oct 9, 2017

Example output

image

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