Last active
October 11, 2017 04:50
-
-
Save Lucretiel/a4bce17277fc2fc7e8df44e228302e88 to your computer and use it in GitHub Desktop.
Sample code showing the use of async functions in Javascript
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
| // Create a promise that is resolved after `timeout` ms | |
| const promiseTimer = timeout => new Promise(resolve => setTimeout(() => resolve(null), timeout)) | |
| async function counter(max) { | |
| for(let i = 0; i < max; i++) { | |
| console.log("Counting:", i) | |
| // This is the important part. "await" allows the function to appear to block; | |
| // other asynchronous work can be done here. This is basically the equivelent | |
| // of a .then on promiseTimer | |
| await promiseTimer(500) | |
| } | |
| console.log("Done") | |
| } | |
| // Calling an async function returns a Promise. | |
| counter(10).then(() => console.log("Finished async function")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment