Skip to content

Instantly share code, notes, and snippets.

@tonkla
Last active February 2, 2020 06:28
Show Gist options
  • Save tonkla/3217277e5da8241ebd41032b8d86e4c0 to your computer and use it in GitHub Desktop.
Save tonkla/3217277e5da8241ebd41032b8d86e4c0 to your computer and use it in GitHub Desktop.
How Asynchronous JavaScript Works?
function print(func, wait) {
console.log(`${func}: ${wait}`)
setTimeout(() => { console.log(`${func}: ${wait}, waited`) }, wait)
}
async function func1() {
await print(1, 1000)
await print(1, 1500)
await print(1, 2000)
}
async function func2() {
await print(2, 2000)
await print(2, 1500)
await print(2, 1000)
}
async function func3() {
await Promise.all([
print(3, 1000),
print(3, 1500),
print(3, 2000),
])
}
async function func4() {
await Promise.all([
print(4, 2000),
print(4, 1500),
print(4, 1000),
])
}
console.log('\nStart func1')
func1()
console.log('\nStart func2')
func2()
console.log('\nStart func3')
func3()
console.log('\nStart func4')
func4()
console.log('')
Start func1
1: 1000
Start func2
2: 2000
Start func3
3: 1000
3: 1500
3: 2000
Start func4
4: 2000
4: 1500
4: 1000
1: 1500
2: 1500
1: 2000
2: 1000
1: 1000, waited
3: 1000, waited
4: 1000, waited
2: 1000, waited
3: 1500, waited
4: 1500, waited
1: 1500, waited
2: 1500, waited
2: 2000, waited
3: 2000, waited
4: 2000, waited
1: 2000, waited
function print(str) {
console.log(str)
}
async function work(func, wait) {
return new Promise(resolve => {
const str = `${func}: ${wait}`
print(str)
setTimeout(() => resolve(`${str}, waited`), wait)
})
}
async function func1() {
print(await work(1, 1000))
print(await work(1, 1500))
print(await work(1, 2000))
}
async function func2() {
print(await work(2, 2000))
print(await work(2, 1500))
print(await work(2, 1000))
}
async function func3() {
const r = await Promise.all([
work(3, 1000),
work(3, 1500),
work(3, 2000),
])
print(r)
}
async function func4() {
const r = await Promise.all([
work(4, 2000),
work(4, 1500),
work(4, 1000)
])
print(r)
}
console.log('\nStart func1')
func1()
console.log('\nStart func2')
func2()
console.log('\nStart func3')
func3()
console.log('\nStart func4')
func4()
console.log('')
Start func1
1: 1000
Start func2
2: 2000
Start func3
3: 1000
3: 1500
3: 2000
Start func4
4: 2000
4: 1500
4: 1000
1: 1000, waited
1: 1500
2: 2000, waited
2: 1500
[ '3: 1000, waited', '3: 1500, waited', '3: 2000, waited' ]
[ '4: 2000, waited', '4: 1500, waited', '4: 1000, waited' ]
1: 1500, waited
1: 2000
2: 1500, waited
2: 1000
2: 1000, waited
1: 2000, waited
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment