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.
function 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 Sleepconsole.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.
function getOne() { return sleep(1000).then(v => 1)}If you await getOne(), youβll see that it takes one second before getOne resolves.
async function test() { console.log('Now')
const one = await getOne() console.log(one)}
test()
Now letβs say you need to wait for three promises. Each promise has a one-second delay.
function getOne() { return sleep(1000).then(v => 1)}
function getTwo() { return sleep(1000).then(v => 2)}
function getThree() { return sleep(1000).then(v => 3)}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.
async function test() { 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.
There are three steps:
- Create the three promises
- Add all three promises into an array
awaitthe array of promises withPromise.all
Hereβs what it looks like:
async function test() { const promises = [getOne(), getTwo(), getThree()] console.log('Now')
const [one, two, three] = await Promise.all(promises) console.log(one) console.log(two) console.log(three)
console.log('Done')}
test()
Welcome! Unfortunately, you donβt have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson