await blocks JavaScript from executing the next line of code until a promise resolves. This may have the unintended consequence of slowing down code execution.
To show this in action, we need to create a delay before resolving the promise. We can create a delay with setTimeoout inside a sleep function.
const sleep = ms => {
return new Promise(resolve => setTimeout(resolve, ms))
}
ms is the number of milliseconds to wait before resolving. If you pass in 1000 into sleep, JavaScript will wait for one second before resolving the promise.
// Using Sleep
console.log('Now')
sleep(1000)
.then(v => {
console.log('After one second')
})
Let’s say we have a function called getOne that takes one second to resolve. To create this delay, we pass 1000 (one second) into sleep. After one second has passed and the sleep promise resolves, we return the value 1.
If you await these three promises in a row, you’ll have to wait for three seconds before all three promises get resolved. This is not good because we forced JavaScript to wait two extra seconds before doing what we need to do.
const test = async _ => {
const one = await getOne()
console.log(one)
const two = await getTwo()
console.log(two)
const three = await getThree()
console.log(three)
console.log('Done')
}
test()
If getOne, getTwo and getThree can be fetched simultaneously, you’ll save two seconds. You can fetch these three promises at the same time with Promise.all.