JavaScript Async Await Masterclass

Pro Members Only

This lesson is available if you have an active subscription.

Alternatively, some member might be able to gift it to you.

If you already have a subscription, you can sign in.

Professional Modern JavaScript Lessons

1.Course Intro
free
⏱️ 1:13
2.Setup & Tooling
free
⏱️ 3:32
3.Debugger Statements and Breakpoints
free
⏱️ 2:17
4.Primitive Data Types and Values
free
⏱️ 3:06
5.JavaScript Variables - let and const
free
⏱️ 4:50
6.Comments in JavaScript
free
⏱️ 2:55
7.JavaScript Identifer Naming
free
⏱️ 2:52
8.Using TypeScript
free
⏱️ 4:26
9.JavaScript String Masterclass
free
⏱️ 9:29
10.JavaScript Boolean Type
⏱️ 6:45
11.Missing Guide to JavaScript Numbers
⏱️ 15:28
12.JavaScript Objects Demystified
⏱️ 13:33
13.Functions in JavaScript
⏱️ 20:25
14.JavaScript Arrays Masterclass
⏱️ 22:31
15.JavaScript If Else Statements and Best Practices
⏱️ 6:13
16.JavaScript Conditional Expressions
⏱️ 8:38
17.JavaScript Loose vs Strict Equality
⏱️ 4:02
18.Truthy vs Falsy in JavaScript
⏱️ 3:44
19.Concept of JavaScript Nullish and Unification
⏱️ 5:51
20.JavaScript Classes - Object Oriented Programming
⏱️ 10:30
21.JavaScript Error Handling and Exceptions
⏱️ 13:21
22.JavaScript Nullish Operators
⏱️ 5:48
23.JavaScript Switch Statement Masterclass
⏱️ 8:07
24.JavaScript For Loop Iteration Simplified
⏱️ 10:59
25.JSON Masterclass
⏱️ 7:59
26.JavaScript While and Do While Loops
⏱️ 2:52
27.JavaScript Date and Time Simplified
⏱️ 13:16
28.this in JavaScript
⏱️ 12:04
29.JavaScript Tagged Templates Masterclass
⏱️ 5:48
30.Promises in JavaScript
⏱️ 10:01
31.JavaScript Async Await Masterclass
⏱️ 9:00
32.JavaScript Symbols Demystified
⏱️ 7:25
33.JavaScript Iterators and Iterables
⏱️ 8:50
34.JavaScript Generators Simplified
⏱️ 9:17
35.JavaScript Prototype - The Secret Guide
⏱️ 11:21
36.JavaScript Set Builtin Data Structure
⏱️ 9:52
37.JavaScript Map Builtin - HashMap Magic
⏱️ 10:38
38.JavaScript Deferred Promise Pattern - withResolvers
⏱️ 3:35
39.Cloning and Deep Copying in JavaScript
⏱️ 3:14
40.JavaScript Async Await Sequencing and Execution Masterclass
⏱️ 10:31
41.JavaScript Memory Management Masterclass
⏱️ 5:26
42.JavaScript WeakMap Demystified
⏱️ 8:58
43.JavaScript bigint Masterclass
⏱️ 5:35
44.JavaScript WeakSet Explained with Examples
⏱️ 7:47
45.JavaScript Regular Expressions Masterclass
⏱️ 17:54
46.JavaScript Weak References Demystified
⏱️ 5:29
47.JavaScript Memory Leaks Demonstrations and Fixes
⏱️ 6:01
48.Semicolon Free Coding in JavaScript
⏱️ 3:46
49.JavaScript Modules Masterclass
⏱️ 11:36

JavaScript Async Await Masterclass

Subscription Required

You must have an active subscription to access this content.
If you already have a subscription, you can sign in.

async

async function funcDeclaration() { }
const funcExpression = async function () { }
const arrowExpression = async () => { }
class Class { async method() { } }

console.log(funcDeclaration()); // Promise
console.log(funcExpression()); // Promise
console.log(arrowExpression()); // Promise
console.log(new Class().method()); // Promise

funcDeclaration().then(v => console.log(v)); // undefined
funcExpression().then(v => console.log(v)); // undefined
arrowExpression().then(v => console.log(v)); // undefined
new Class().method().then(v => console.log(v)); // undefined

Promise Return Value

async function simple() {
return 'simple';
}
simple()
.then(v => console.log(v)); // 'simple'

async function accepted() {
return new Promise(
res => setTimeout(() => res('fulfilled'), 1000)
);
}
accepted()
.then(v => console.log(v)); // 'fulfilled'

async function denied() {
return new Promise(
(_, rej) => setTimeout(() => rej(new Error('rejected')), 2000)
);
}
denied()
.catch(v => console.log(v.message)); // 'rejected'

Error to Rejection

async function implicit() {
magic();
}
const result = implicit();
console.log('isPromise:', result instanceof Promise); // isPromise: true
result.catch(e => console.log(e.message)); // 'magic is not defined'

async function explicit() {
throw new Error('fail');
}
explicit().catch(e => console.log(e.message)); // 'fail'

await Operator

async function main() {
const raw = 'not-a-promise';
const funsies = await raw;
console.log(funsies); // 'not-a-promise'

const fulfilled = new Promise(resolve => setTimeout(() => {
resolve('fulfilled');
}, 2000));
const fulfilledResult = await fulfilled;
console.log('result:', fulfilledResult); // result: 'fulfilled'

const rejected = new Promise((_, reject) => setTimeout(() => {
reject(new Error('rejected'));
}, 2000));
try {
const rejectedResult = await rejected; // 💥
console.log('result:', rejectedResult); // skipped ⏭️
} catch (e) {
console.log('error message:', e.message); // error message: 'rejected'
}
}; main();

Example delay

/**
* Call cb three times in sequence, each time after 1s delay
*/
const wait = (ms) => new Promise(
(res) => setTimeout(res, ms)
);

async function main(cb) {
await wait(1000);
cb();
await wait(1000);
cb();
await wait(1000);
cb();
}
main(() => console.log('hi'));

Example API calls

main();
async function main() {
const userResponse = await fetch('https://api.github.com/users/basarat');
const user = await userResponse.json();
console.log('Name:', user.name);
console.log('Twitter:', user.twitter_username);

const { organizations_url } = user;
const orgsResponse = await fetch(organizations_url);
const orgs = await orgsResponse.json();
console.log('Organizations:', orgs.map((org) => org.login));
}
javascript
typescript
react
playwright

Enjoy free content straight from your inbox 💌

No spam, unsubscribe at any time.

Transcript

00:00

JavaScript was popular even before Async eight, back when life was full of callbacks. But now Async eight is fairly mainstream and it's actually quite easy to use an added score. We have the async keyword to specify that a function is an async function. We use the async keyword and you can use it pretty much whenever you would create a function. For example, a function declaration, a function expression, even arrow expressions and even class methods. A key thing to remember with async functions is that they always return a promise. So even though these functions don't have a return statement, we will still get back a promise when we invoke them.

00:36

This promise will resolve based on the returned value. And as we know when a standard synchronous function, it does not have a return statement. JavaScript still returns the special value of undefined. So all of these promises will actually resolve to that same special value of undefined. We can verify this behavior by running this code, and as you can see, we get back four promises that resolve the value of undefined. Just like when we resolve one promise to another promise, the fates of the two become a one and the same. It also applies to asy function return values. When an async function does not return a promise, for example,

01:10

here we are returning a simple string, then the promise from the async function immediately resolves to that value. However, when an asing function does return a promise, then the fate of the returned value is going to be the same as the fate of the returned promise. In this particular case, the promise that we are returning gets fulfilled with the string value of fulfilled. So of course, that is what people see in the then callback for the returned value. However, if the promise that is returned from the async function gets rejected, then the return value will also get rejected. And here we are handling the scenario with a simple catch and logging out the

01:44

error message. So now if you run this code, we see the simple value immediately and fulfilled gets resolved, and then the rejected value goes into the catch. Pacing functions gracefully handle all errors that occur inside of them and turn them into nice and easy to deal with. Rejected promises. To recap, when we have a standard synchronous function and we make a mistake, for example, we are invoking a function that does not exist. Magic is not even defined. If we invoke it, then it'll result in a synchronous throw from the JavaScript one time, which must be caught with a dry catch. Ay functions, however,

02:18

always return a promise, which means that they do not throw an error synchronously. So it is perfectly safe to call an A function and store the value in a result. And as we've seen, what we really get back is a promise of the result. So if an error does occur in the execution of the async function, what happens is that the promise that is returned is what gets rejected. So in this particular case, the result promise will get rejected with an error, but the JavaScript runtime, and of course the error message will be the same as what we saw before, which is magic is not defined. Now of course, magic is not defined as sort of a coding error,

02:51

and the JavaScript runtime is what is throwing that error. But we can throw an error ourselves as well using the throw key word, and this tool will get Converted into a promise rejection. This is why we have always been using an error object whenever we are rejecting a promise. Because a promise rejection is an asynchronous version of a synchronous throw, and we've already discussed during error handling that you should always throw an error object and not some random string. Now let's run this code to verify it works as expected. And of course it does. We have our synchronous error caught with the message logged. We have our asynchronous errors caught as promises and logged using catch

03:26

handlers. Now that we understand how the async keyword works, we can take a look at the await keyword and how it behaves in an async function. We start off with a simple asing function that allows us to use the await keyword and to kick us off. Let's look at when we use the await keyword on something that is not a promise. There is absolutely no point in doing this. This await operator is completely useless. It just gives back whatever is passed in, and as you will see, itll be exactly the same as the original string. The real use case of the await operator is when we use it on something that is a

04:00

promise. For example, hey, we have a promise that gets fulfilled to the string fulfilled after two seconds. If we use the await keyword before this promise, the code execution within this asing function will essentially pause till the promise fate is settled. In this particular case, this promise will get fulfilled and the await keyword will give us back the fulfilled value. So for this particular example, if we lock out the fulfilled result, we should see that string fulfilled. Let's create another promise. But this time we will make this promise reject with an error After two seconds, if the promise that we are awaiting results in a rejection,

04:34

then the JavaScript on time will throw a synchronous error into this ay function. The thing that will be thrown will be exactly the same as the value used for the promised rejection. If you don't catch that error, it will go all the way to the ay function result, which of course will be that rejection value, but we can catch it within an asy function by using the standard dry catch. Here we are using a weight on the promise that will eventually get rejected, but we have been smart enough to wrap it up within a try. And of course, as soon as this error gets thrown, no further statements within the trial will execute and it'll jump straight to

05:08

the corresponding catch block. So within our catch, we should see that error message, which of course is that string rejected. If you run this code, you can see that for not a promise, there's no point in using the await keyword. Then we wait for two seconds till the second promise gets resolved and we get back the result and then we wait two more seconds till the next promise gets rejected, and we catch that within a catch handler. We've looked at how even promises by themselves clean up the callback hell and asing away, just takes that to the next level and brings the true convenience of everyday synchronous programming to the async world.

05:42

Consider the simple task of creating a function that takes a callback and then it should call it three times each time. After a delay of one second, we create a simple utility function that we've seen a few times, which simply takes a millisecond value and then returns a promise, which We eventually resolve after those milliseconds have passed by using a set timeout. Now let's work on the function that meets the requirements specified. Of course, it's going to be an async function that's going to take that callback, and now we can just create a promise using our wait digital that will resolve after one second and use the wait keyword to pause execution till that promise resolves. Once that promise resolves,

06:18

we will invoke our callback and then we will again wait for one more second. Then again, invoke the callback and then do it one more time. Let's demo this main function by giving it a simple callback that logs the message Hi. And now when we run this code, we get that hi message each time after a delay of one second, you might argue that what's the big deal? I could do this pretty easily with the promised then chain. But what Aate really unlocks is the ability to do any synchronous programming. You want like a fall loop that does the same thing five times or any number of times that you provide.

06:51

And in each iteration we have that simple AWAI for one second followed by a call to the callback. With Aate, you almost don't even have to think about the fact that you are writing asynchronous code. Aate has made asynchronous programming extremely easy and it's most apparent when working with backend APIs over a network. For this demo, we will use the simple a p i provided by GitHub, which is API github.com/users, and you can provide any user id. For example, here I'm providing my own, and you can see the sample response and there is a lot of stuff on screen, but let's focus in on how we could read the name the Twitter username,

07:28

and then make another request to the organization's U R L to read all the organizations that this particular user belongs to. We will be working within an async main function, and we start off by using a built-in a p I called Fetch. And this a p i is available on browsers as well as node js. It takes a simple U R L string and returns a promise that eventually resolves to an HST T P response object. As we know that the body of this response is json, we can actually convert it into a JavaScript object by using the JSON method on the response object, which again returns a promise.

08:01

So we simply await that as well. This gives us a JavaScript object version of the JSON payload that we were looking at, and we can easily read the name and the Twitter username properties. We can also read the organization U R L, and let's make another fetch request using the organization U R L to get another orgs response. And again, pass that from JSON by using the J S N method. And this time we will get back an org's array. Each item in the array has a login member, which is basically the name of the organization. So for the organizations, we simply log out the individual org login properties.

08:37

And now for the moment of truth, let's open up the terminal and execute this code using Node jss. And as you can see, we can read the name, the Twitter and the organization names, and this was all pretty simple thanks to promises. The Fetch a p I, which works on promises and Async Await. I hope you enjoyed this tutorial. As always, thank you for joining me, and I will see you in the next one.

Professional Modern JavaScript

Professional Modern JavaScript

1.Course Intro
free
⏱️ 1:13
2.Setup & Tooling
free
⏱️ 3:32
3.Debugger Statements and Breakpoints
free
⏱️ 2:17
4.Primitive Data Types and Values
free
⏱️ 3:06
5.JavaScript Variables - let and const
free
⏱️ 4:50
6.Comments in JavaScript
free
⏱️ 2:55
7.JavaScript Identifer Naming
free
⏱️ 2:52
8.Using TypeScript
free
⏱️ 4:26
9.JavaScript String Masterclass
free
⏱️ 9:29
10.JavaScript Boolean Type
⏱️ 6:45
11.Missing Guide to JavaScript Numbers
⏱️ 15:28
12.JavaScript Objects Demystified
⏱️ 13:33
13.Functions in JavaScript
⏱️ 20:25
14.JavaScript Arrays Masterclass
⏱️ 22:31
15.JavaScript If Else Statements and Best Practices
⏱️ 6:13
16.JavaScript Conditional Expressions
⏱️ 8:38
17.JavaScript Loose vs Strict Equality
⏱️ 4:02
18.Truthy vs Falsy in JavaScript
⏱️ 3:44
19.Concept of JavaScript Nullish and Unification
⏱️ 5:51
20.JavaScript Classes - Object Oriented Programming
⏱️ 10:30
21.JavaScript Error Handling and Exceptions
⏱️ 13:21
22.JavaScript Nullish Operators
⏱️ 5:48
23.JavaScript Switch Statement Masterclass
⏱️ 8:07
24.JavaScript For Loop Iteration Simplified
⏱️ 10:59
25.JSON Masterclass
⏱️ 7:59
26.JavaScript While and Do While Loops
⏱️ 2:52
27.JavaScript Date and Time Simplified
⏱️ 13:16
28.this in JavaScript
⏱️ 12:04
29.JavaScript Tagged Templates Masterclass
⏱️ 5:48
30.Promises in JavaScript
⏱️ 10:01
31.JavaScript Async Await Masterclass
⏱️ 9:00
32.JavaScript Symbols Demystified
⏱️ 7:25
33.JavaScript Iterators and Iterables
⏱️ 8:50
34.JavaScript Generators Simplified
⏱️ 9:17
35.JavaScript Prototype - The Secret Guide
⏱️ 11:21
36.JavaScript Set Builtin Data Structure
⏱️ 9:52
37.JavaScript Map Builtin - HashMap Magic
⏱️ 10:38
38.JavaScript Deferred Promise Pattern - withResolvers
⏱️ 3:35
39.Cloning and Deep Copying in JavaScript
⏱️ 3:14
40.JavaScript Async Await Sequencing and Execution Masterclass
⏱️ 10:31
41.JavaScript Memory Management Masterclass
⏱️ 5:26
42.JavaScript WeakMap Demystified
⏱️ 8:58
43.JavaScript bigint Masterclass
⏱️ 5:35
44.JavaScript WeakSet Explained with Examples
⏱️ 7:47
45.JavaScript Regular Expressions Masterclass
⏱️ 17:54
46.JavaScript Weak References Demystified
⏱️ 5:29
47.JavaScript Memory Leaks Demonstrations and Fixes
⏱️ 6:01
48.Semicolon Free Coding in JavaScript
⏱️ 3:46
49.JavaScript Modules Masterclass
⏱️ 11:36