COVID19 Lockdown Dev Log – Day 34, Async Await Basics
What I Worked On
The Taskmanager app.
What I Learned
In JavaScript, a function will return ‘undefined’, if it does not have a return value. For example like the function below:
const doSomething = () => {
const a = 2
const b = 4
result = a + b
}
Output:
undefined
If we make the function asynchronous it will return a Promise:
// Tip: If you return a 'throw new Error()' the Promise will reject.
const doSomethingAsync = async () => {
return 'André'
}
Output:
Promise { 'André' }
So André, why is this a smart thing? In short, using async/await can help you avoid writing code with complex Promise chaining (writing multiple then()s). Let’s take an example of Promise chaining and rewrite it with async/await. Let’s first create a function to use:
//this function returns a Promise. It checks that 'a' and 'b'
//aren't negative and resolves the Promise with the sum of the numbers
const add = (a, b) => {
return new Promise((resolve,reject) => {
// Simulate async operation
setTimeout(() => {
if (a < 0 || b < 0) {
return reject("Numbers can't be negative")
}
resolve(a + b)
}, 2000)
})
}
Now let’s chain some Promises where we use the add() function to add numbers together:
add(10,20).then((sum) => {
console.log(sum)
return add(sum, 20)
}).then((sum2) => {
console.log(sum2)
return add(sum2, 40)
}).then((sum3) => {
console.log(sum3)
return add(sum3, 60)
}).catch((error) => {
console.log(error)
})
That’s a lot of then()s. Let’s make it cleaner by modifying the doSomethingAsync() function with async/await:
const doSomethingAsync = async () => {
const sum = await add(1, 99)
const sum2 = await add(sum, 50)
const sum3 = await add(sum2, 50)
return sum3
}
doSomethingAsync ().then((result) => {
console.log('result: ', result)
}).catch((error) => {
console.log('error: ', error)
})
Ah! Much cleaner 😀 If one of the await calls rejects/fails, the ‘reject’ in the ‘add()’ function fires and the Promise chaining stops where it failed.
What Distracted Me During The Day
- Had some laundry to take care off in between coding sessions 😀
Resources
- Andrew Mead – https://mead.io/