Skip to content

Instantly share code, notes, and snippets.

@paramaggarwal
Last active March 22, 2022 03:51
Show Gist options
  • Save paramaggarwal/9d23e0b04179b17d69484a43c5020be2 to your computer and use it in GitHub Desktop.
Save paramaggarwal/9d23e0b04179b17d69484a43c5020be2 to your computer and use it in GitHub Desktop.
Trying out some concepts of Promise and async/await in Javascript.
function waiter(str) {
return new Promise((resolve, reject) => {
return setTimeout(() => resolve(str), 1000)
})
}
await waiter('one').then((res) => waiter(res + 'two'))
// 'onetwo'
await waiter('one').then((res) => { waiter(res + 'two') })
// undefiend
await waiter('one').then(async (res) => (await waiter(res + 'two')))
// 'onetwo'
await waiter('done')
// 'done'
await waiter('done').then(val => console.log(val))
// 'done'
// undefined
await waiter('done').then(val => (val + 2))
// 'done2' [after one sec]
await waiter('done').then(val => waiter(val + 2))
// 'done2' [after two secs]
for (let i=0; i<5; i++) {
await waiter('wait: '+i)
console.log('log: '+i)
}
// log: 0
// log: 1
// log: 2
// log: 3
// log: 4
for (let i=0; i<5; i++) {
await waiter('wait: '+i).then(console.log)
console.log('log: '+i)
}
// wait: 0
// log: 0
// wait: 1
// log: 1
// wait: 2
// log: 2
// wait: 3
// log: 3
// wait: 4
// log: 4
function waiterTimed(str) {
const startTime = Date.now()
console.log("log start:", str)
return new Promise((resolve, reject) => {
return setTimeout(() => {
const endTime = Date.now()
console.log("log end:", str, endTime - startTime)
resolve(str)
}, 1000)
})
}
await waiterTimed('one').then((res) => waiterTimed(res + 'two'))
// 'onetwo'
for (let i=0; i<5; i++) {
await waiterTimed('wait: '+i).then(console.log)
console.log('log: '+i)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment