# Async and await
# Async
Syntactical sugar for promises. Same as returning a new promise object in function.
- Async function always return a promise.
- If the function returns a value, the promise will be resolved with that value.
- If the function throws an exception, the promise will be rejected.
async function greet(){
return 'hi'
}
// This returns promise resolved with value 'hi'
greet().then((val) => {
console.log('resolved with:', val)
})
// resolved with: hi
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
function add(x,y){
if (typeopf x !== 'number' || typeof y !== 'number'){
throw 'X and Y must be numbers!'
}
return x + y;
}
// this returns either a value or throws an error
async function add(x,y){
if (typeopf x !== 'number' || typeof y !== 'number'){
throw 'X and Y must be numbers!'
}
return x + y;
}
// this returns a promise object with either resolved or rejected value
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
![image-20210125225854671](./async await.assets/image-20210125225854671.png)
# Error handling
async function add(x,y){
if (typeopf x !== 'number' || typeof y !== 'number'){
throw 'X and Y must be numbers!'
}
return x + y;
}
add('e', 'r')
.then((val)=> {
console.log('resolved with', val)
})
.catch((err) => {
console.log('rejected with', err)
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Await
- Can only be used inside function declared with async
- await will pause the function until the promise is resolved
- Used instead of
then
.
async function getPlanets(){
const res = axios.get('https://swapi.co/api/planests/')
console.log(res.data)
}
// undefined
async function getPlanets(){
const res = await axios.get('https://swapi.co/api/planests/')
console.log(res.data)
}
// good!
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
# Error handling
async function getPlanets(){
const res = await axios.get('https://swapi.co/api/planests/')
console.log(res.data)
}
// catch
getPlanets.catch((err)=>{
console.log(err)
})
// try catch
async function getPlanets(){
try {const res = await axios.get('https://swapi.co/api/planests/')
console.log(res.data)
} catch(err){
console.log('caught', err)
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# Parallel vs Sequential
![image-20210125231132821](./async await.assets/image-20210125231132821.png)