Javascript Promises vs Async Await EXPLAINED (in 5 minutes)

Roberts Dev Talk
18 Aug 202105:49

Summary

TLDRIn this informative video, Chris Roberts explores JavaScript Promises, explaining their necessity for handling asynchronous operations. He demonstrates how to use 'then' and 'catch' methods to manage promises and introduces the 'async' and 'await' keywords for cleaner, more sequential code execution. With a practical example involving an API request, he illustrates the process of fetching data and handling errors, ultimately simplifying complex asynchronous code into a more readable format.

Takeaways

  • 🌟 JavaScript Promises are used for handling asynchronous operations, representing a future completion or failure of a task.
  • 🔗 The 'then' method is used to handle the successful completion of a Promise, allowing access to the result of the asynchronous operation.
  • 🚫 The 'catch' method is used to handle any errors that occur during the execution of the Promise, providing a way to deal with failures.
  • 📚 Promises are compared to a real-world scenario, like ordering coffee at a restaurant, where you must wait for the coffee to be brought to you.
  • 🛠 The 'axios' library is used in the example to demonstrate how to make API requests and handle the returned Promises.
  • 📝 The script explains that using Promises can lead to 'callback hell', where nested callbacks make the code difficult to read and maintain.
  • 🔄 The 'async' and 'await' keywords are introduced as a way to simplify asynchronous code, making it more readable and sequential.
  • 🛑 The 'await' keyword is used to pause the execution of the function until the Promise is resolved, allowing for a more straightforward code flow.
  • 🔀 The 'try...catch' block is used in conjunction with 'async' functions to handle errors, similar to how it's used in synchronous code.
  • 🎥 The video aims to demystify the use of Promises and async/await in JavaScript, providing practical examples and clear explanations.

Q & A

  • What is the main topic of the video by Chris Roberts?

    -The main topic of the video is an explanation of JavaScript Promises, including why they are needed, how to use the 'then' and 'catch' methods, and how to convert code using these to using 'async' and 'await' keywords.

  • Why are JavaScript Promises used in programming?

    -JavaScript Promises are used to handle asynchronous operations, such as database calls, file operations, or API requests, which do not return results immediately but instead return a promise that will eventually complete or fail.

  • What is the real-world analogy used in the video to explain Promises?

    -The real-world analogy used is ordering coffee at a restaurant. Just as you wait for the waiter to bring your coffee, in JavaScript, you wait for a promise to be fulfilled with the result of an asynchronous operation.

  • What is the purpose of the 'then' method in Promises?

    -The 'then' method is used to specify what should happen when the promise is fulfilled. It receives the result of the task as a parameter and allows you to run code with that result.

  • What is the purpose of the 'catch' method in Promises?

    -The 'catch' method is used to handle any errors that occur while processing the promise. It receives the error as a parameter and allows you to run error-handling code.

  • How does the 'await' keyword work with Promises?

    -The 'await' keyword is used to wait for a promise to be resolved before moving on to the next line of code. It allows for a cleaner and more synchronous-looking code structure when dealing with asynchronous operations.

  • What is required for a function to use the 'await' keyword?

    -The 'await' keyword must be used inside a function that is marked with the 'async' keyword, indicating that the function contains asynchronous code.

  • How does the video demonstrate the use of Promises with an example?

    -The video uses an example of an app that suggests activities when you are bored, making a request to a 'board' API and logging the suggested activity to the console, demonstrating the use of 'then', 'catch', and 'await'.

  • What is the issue with the initial code example in the video?

    -The initial code example fails because it tries to access properties ('data' and 'activity') on a response object that is not structured as expected, leading to an error.

  • How does the video address the problem of sequential code execution with Promises?

    -The video introduces the 'async' and 'await' keywords as a solution to make the code neater and more readable, allowing for sequential execution of asynchronous code.

  • How does the video handle errors in the context of 'async' and 'await'?

    -With 'async' and 'await', errors are handled using a standard try-catch block. If an error occurs, it is caught and can be logged or handled within the catch block.

Outlines

00:00

🌟 JavaScript Promises and Asynchronous Operations

This paragraph introduces JavaScript Promises as a way to handle asynchronous operations such as database calls, file operations, and API requests. It explains that Promises represent the eventual completion or failure of these operations and their resulting values. The analogy of a waiter at a restaurant promising to bring coffee is used to illustrate the concept. The paragraph also discusses the use of the 'then' and 'catch' methods to handle the resolution or rejection of a Promise, and provides an example of using the Axios library to make an API request, handle the response, and catch any errors.

05:02

🔄 Enhancing Code Readability with Async and Await

The second paragraph focuses on improving the readability and manageability of asynchronous code in JavaScript. It contrasts the traditional Promise chaining with the use of 'async' and 'await' keywords, which allow for a more sequential and straightforward approach to handling asynchronous operations. The paragraph demonstrates how to refactor a Promise chain into an 'async' function using 'await' to pause execution until the Promise is resolved. It also addresses error handling with 'try' and 'catch' blocks in the context of 'async' functions, using the HTTP status API to simulate different error scenarios and showcasing how errors are caught and logged.

Mindmap

Keywords

💡JavaScript Promises

JavaScript Promises are a fundamental concept in asynchronous programming. They represent a value that may not be available yet but will be resolved at some point in the future or fail to be resolved. In the video, Chris Roberts uses the analogy of ordering coffee at a restaurant to explain how a promise works. Just as you wait for the waiter to bring your coffee, in JavaScript, you wait for a promise to be fulfilled with the result of an asynchronous operation, such as fetching data from an API.

💡Asynchronous Operations

Asynchronous operations are tasks that do not block the execution of the program while they are being completed. In JavaScript, these operations are common when dealing with I/O tasks like reading files, making network requests, or interacting with databases. The video script mentions that promises are used to handle the eventual completion or failure of such operations, which do not return results immediately but at some later point in time.

💡then and catch methods

The 'then' and 'catch' methods are part of the Promise API in JavaScript. The 'then' method is used to handle the fulfillment of a promise, allowing you to specify what should happen when the promise is successfully resolved. The 'catch' method is used to handle any errors that occur if the promise is rejected. In the script, these methods are demonstrated as a way to process the result of an API request or catch any errors that might occur during the request.

💡axios

Axios is a popular HTTP client library for making requests in JavaScript. It is used in the video script to demonstrate how to make an API request and handle the response with promises. Axios returns a promise when you make a request, and you can use the 'then' and 'catch' methods to process the response or handle errors, as shown when the script logs the suggested activity to the console.

💡async and await keywords

The 'async' and 'await' keywords are used in JavaScript to write asynchronous code that can be read and understood more like synchronous code. 'async' makes a function return a promise implicitly, and 'await' is used to pause the execution of the async function until the promise is resolved or rejected. In the video, Chris Roberts demonstrates how to refactor the promise chain into an async function using 'await', making the code cleaner and more readable.

💡API

An API (Application Programming Interface) is a set of rules and protocols for building and interacting with software applications. In the context of the video, an API is used to fetch suggestions for activities when the user is bored. The script uses the 'board api' as an example to illustrate how to make a request and handle the response using promises and async/await.

💡Sequential Execution

Sequential execution refers to the order in which statements are executed in a program, one after another. The video script contrasts this with asynchronous execution, where operations like API calls do not block the execution flow. The use of 'async' and 'await' allows developers to write code that appears to execute sequentially, even though it's dealing with asynchronous operations under the hood.

💡HTTP Status API

The HTTP Status API is a tool used in the video to simulate different HTTP response statuses for testing purposes. It allows developers to request specific status codes, such as 404 Not Found or 500 Server Error, to see how their code handles these scenarios. In the script, Chris Roberts uses the HTTP Status API to demonstrate how the 'catch' method can be used to handle errors like a 404 error.

💡Error Handling

Error handling is a critical aspect of programming that involves anticipating and responding to errors that occur during the execution of a program. In the video, error handling is demonstrated using the 'catch' method of promises and try/catch blocks in async functions. These mechanisms allow the developer to catch and handle errors, such as network issues or data processing errors, ensuring the program can gracefully deal with unexpected situations.

💡try catch block

A 'try catch' block is a standard error-handling construct in many programming languages, including JavaScript. The 'try' block contains code that might throw an exception, and the 'catch' block contains code to handle the exception if one occurs. In the video, Chris Roberts shows how to use a try/catch block with async functions to handle errors that occur when promises are awaited, providing a way to catch and log errors that might occur during asynchronous operations.

Highlights

Introduction to JavaScript Promises and their necessity in handling asynchronous operations.

Explanation of how JavaScript code executes sequentially with simple types like strings and numbers.

Real-world analogy of a restaurant waiter to explain the concept of a Promise in JavaScript.

Description of a Promise as an object representing the eventual completion or failure of an asynchronous operation.

Example of using the axios request library to make an API call and the immediate return of a Promise.

Misunderstanding of the response object in a Promise and the resulting error.

Introduction of the 'then' method for handling the successful completion of a Promise.

Introduction of the 'catch' method for handling errors in a Promise.

Demonstration of chaining 'then' and 'catch' methods to handle results and errors.

Explanation of the immediate execution of code following a Promise chain and its implications.

Introduction of the 'async' and 'await' keywords for cleaner asynchronous code.

Usage of 'await' to wait for a Promise to resolve before moving to the next line of code.

Inclusion of 'async' functions to utilize 'await' and improve code readability.

Handling errors with a standard try-catch block in 'async' functions.

Demonstration of catching and logging errors using the try-catch block.

Conclusion summarizing the benefits of using Promises, 'async', and 'await' in JavaScript.

Call to action for viewers to subscribe for more educational content.

Transcripts

play00:00

in this video i'll show you what

play00:01

javascript promises are why we need them

play00:04

how to use the special then and catch

play00:06

methods and then how to convert the same

play00:07

code to using the much need to async and

play00:09

await keywords my name is chris roberts

play00:12

when dealing with simple types in

play00:14

javascript such as strings and numbers

play00:16

our code executes sequentially we can

play00:18

assign a string a number and then

play00:20

combine the two values together straight

play00:22

away everything is nice and simple

play00:24

however when writing real world code we

play00:27

often make calls to databases open files

play00:29

and speak to remote apis over the

play00:31

internet now longer running tasks like

play00:34

this will usually not return the results

play00:35

straight away they will rather return a

play00:37

promise now i promise is a special type

play00:40

of object in javascript that represents

play00:42

the eventual completion or failure of an

play00:44

asynchronous operation and its resulting

play00:46

value if this sounds a little bit hard

play00:48

to understand maybe we can imagine it as

play00:50

a real world scenario imagine you are at

play00:53

a restaurant having dinner and you ask

play00:54

the waiter to bring you another cup of

play00:56

coffee the waiter promises to come back

play00:58

with your coffee however you can't drink

play01:01

it at that point you have to wait until

play01:03

he returns with your coffee and the

play01:04

promise is fulfilled and this is the

play01:06

same sort of concept in javascript if

play01:08

for example you request some information

play01:10

from a remote api then you will be

play01:12

immediately given a promise that task

play01:14

will eventually either complete or fail

play01:17

it's not until sometime later the

play01:19

promise itself is actually resolved or

play01:21

rejected and you can use a result of

play01:23

that promise so let's have a look at an

play01:25

example in javascript now imagine you

play01:27

were building an app that suggested

play01:28

things to do when you were bored so

play01:30

you'll be using the board api and the

play01:32

board api just returns random

play01:34

suggestions of things that you can do

play01:36

along with a number of participants

play01:37

required let's just keep it really

play01:39

simple by going to the api getting a

play01:41

suggested activity and then logging out

play01:43

the activity to the console now in this

play01:45

example we're using the axios request

play01:47

library and the get method returns

play01:49

immediately but that doesn't mean that

play01:51

the request has finished processing what

play01:53

we have is a promise that the request

play01:55

will be fulfilled in the future so this

play01:58

code will fail because the response

play02:00

object is not what we're expecting so

play02:02

the data and activity properties do not

play02:04

exist so is there any way for us to get

play02:06

access to the result of the request and

play02:09

run code when it returns well thankfully

play02:11

yes because javascript gives us a couple

play02:13

of ways to wait until a task is finished

play02:16

and use the result or catch any errors

play02:18

that occur the first way is by using a

play02:20

couple of special methods on the promise

play02:22

object the first one is called then then

play02:25

is called when the task completes as a

play02:27

parameter it receives the result of the

play02:29

task and the catch method is called if

play02:32

anything goes wrong while processing our

play02:34

request and this receives the error that

play02:36

occurred as a parameter

play02:38

so let's replace this code use the axios

play02:40

request library and call the get method

play02:43

now because get returns a promise object

play02:45

we can immediately chain on the then

play02:47

method inside our then method we'll log

play02:50

out to the console the suggested

play02:51

activity from the api then after this we

play02:54

can chain on the catch method this will

play02:56

be called if anything goes wrong while

play02:57

processing our request let's just log

play02:59

out to the console the error message

play03:00

that is returned then we can run this

play03:03

and see that our console log executes in

play03:05

the right place

play03:06

now to simulate an error occurring in

play03:08

our request let's replace the url with a

play03:11

call to the http status api this is

play03:14

really useful for testing different

play03:15

status codes and we'll just request a

play03:17

404 not found error we can run this

play03:20

again and see that our error is neatly

play03:23

caught by our catch method and printed

play03:24

out to the console it's worth noting

play03:27

that any code placed after this promised

play03:29

chain will be executed immediately so if

play03:31

we put a console log here at the bottom

play03:33

we'd expect it to be written out after

play03:36

our request returns but actually it gets

play03:37

printed out first this is because only

play03:40

the code inside the then and catch

play03:42

methods is executed after the request

play03:44

returns

play03:45

now this works fine however as you can

play03:46

see the code isn't particularly nice to

play03:48

look at and if you had a lot of

play03:50

complicated code inside your methods

play03:51

things would soon start to get quite

play03:53

unwieldy so what we need really is a way

play03:55

of receiving the results of our promises

play03:57

sequentially just as if we were dealing

play03:59

with simple types like strings and

play04:01

numbers and this is where the await

play04:03

keyword comes in and await does exactly

play04:06

what it says it allows us to wait until

play04:08

the promise has completed before moving

play04:10

on to the next line this makes our code

play04:12

a lot neater and easier to read

play04:14

javascript requires our await keywords

play04:16

be used inside functions marked with the

play04:19

async keyword so let's replace our

play04:21

promise chain with a function marked

play04:23

with the async keyword let's call it

play04:25

getactivity and now we're going to make

play04:26

the same request to our board api but

play04:29

notice we have the await keyword before

play04:31

the method call and immediately after on

play04:34

our next line of code we can use the

play04:35

response and log out to the console the

play04:37

suggested activity this console logline

play04:40

will not run until the promise resolves

play04:42

or is returned we can call our get

play04:44

activity and we'll see that our code

play04:46

executes perfectly

play04:48

now because the awake keyword allows us

play04:50

to move this kind of asynchronous code

play04:52

back into the main flow of our app we

play04:53

don't have access to this specialized

play04:55

catch method to handle any errors that

play04:57

occur so what happens if something goes

play04:59

wrong well because our code executes

play05:01

sequentially we can just wrap this with

play05:03

a normal try catch block inside our

play05:06

catch method we can just log out to the

play05:07

console the error less time to simulate

play05:10

a server error we'll use the http status

play05:12

api again and this time we'll request a

play05:14

500 server error we'll call our get

play05:16

activity

play05:17

notice our request error has been nicely

play05:20

caught and logged out to the console i

play05:22

hope that has helped to demystify using

play05:24

promises and the async and await

play05:26

keywords in javascript if you enjoy this

play05:28

kind of content then we make videos

play05:30

every week so make sure to subscribe and

play05:32

ring that bell icon so you never miss

play05:34

out on one of our videos thank you so

play05:36

much for watching and we'll see you next

play05:37

time

play05:38

[Music]

Rate This

5.0 / 5 (0 votes)

関連タグ
JavaScriptPromisesasync/awaitAsynchronousAPI CallsError HandlingProgramming TutorialCode ExecutionChris RobertsWeb Development
英語で要約が必要ですか?