Skip to content

Instantly share code, notes, and snippets.

@Lucretiel
Last active October 11, 2017 04:50
Show Gist options
  • Select an option

  • Save Lucretiel/a4bce17277fc2fc7e8df44e228302e88 to your computer and use it in GitHub Desktop.

Select an option

Save Lucretiel/a4bce17277fc2fc7e8df44e228302e88 to your computer and use it in GitHub Desktop.
Sample code showing the use of async functions in Javascript
// 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