Skip to content

Instantly share code, notes, and snippets.

@matthewdordal
Last active August 1, 2019 16:13
Show Gist options
  • Save matthewdordal/bf6d29a281d7ee653571852595923d59 to your computer and use it in GitHub Desktop.
Save matthewdordal/bf6d29a281d7ee653571852595923d59 to your computer and use it in GitHub Desktop.
Async/Await and Promises
const P = val => {
return new Promise(resolve => {
setTimeout(() => resolve(val), 1000)
})
}
const usePromise = () => {
console.log('start')
P('async val').then(res => {
console.log(res)
})
console.log('stop')
}
const useAsyncAwait = async () => {
console.log('start')
const res = await P('async val')
console.log(res)
console.log('stop')
}
const useAsyncAwaitWithThen = async () => {
console.log('start')
const res = await P('async val').then(res => {
console.log('inside callback:', res)
return res
})
console.log(res)
console.log('stop')
}
usePromise() // logs 'start' -> 'stop' -> 'async val'
useAsyncAwait() // logs 'start' -> 'async val' -> 'stop'
useAsyncAwaitWithThen() // logs 'start' -> 'inside callback: async val' -> 'async val' -> 'stop'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment