Created
October 9, 2017 15:04
-
-
Save sgb-io/6b33e1b162b5f7ba9801447e430213e8 to your computer and use it in GitHub Desktop.
Example usage of async functions (ES7)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | |
| }) |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example output