Javascript Promises vs Async Await EXPLAINED (in 5 minutes)
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
🌟 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.
🔄 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
💡Asynchronous Operations
💡then and catch methods
💡axios
💡async and await keywords
💡API
💡Sequential Execution
💡HTTP Status API
💡Error Handling
💡try catch block
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
in this video i'll show you what
javascript promises are why we need them
how to use the special then and catch
methods and then how to convert the same
code to using the much need to async and
await keywords my name is chris roberts
when dealing with simple types in
javascript such as strings and numbers
our code executes sequentially we can
assign a string a number and then
combine the two values together straight
away everything is nice and simple
however when writing real world code we
often make calls to databases open files
and speak to remote apis over the
internet now longer running tasks like
this will usually not return the results
straight away they will rather return a
promise now i promise is a special type
of object in javascript that represents
the eventual completion or failure of an
asynchronous operation and its resulting
value if this sounds a little bit hard
to understand maybe we can imagine it as
a real world scenario imagine you are at
a restaurant having dinner and you ask
the waiter to bring you another cup of
coffee the waiter promises to come back
with your coffee however you can't drink
it at that point you have to wait until
he returns with your coffee and the
promise is fulfilled and this is the
same sort of concept in javascript if
for example you request some information
from a remote api then you will be
immediately given a promise that task
will eventually either complete or fail
it's not until sometime later the
promise itself is actually resolved or
rejected and you can use a result of
that promise so let's have a look at an
example in javascript now imagine you
were building an app that suggested
things to do when you were bored so
you'll be using the board api and the
board api just returns random
suggestions of things that you can do
along with a number of participants
required let's just keep it really
simple by going to the api getting a
suggested activity and then logging out
the activity to the console now in this
example we're using the axios request
library and the get method returns
immediately but that doesn't mean that
the request has finished processing what
we have is a promise that the request
will be fulfilled in the future so this
code will fail because the response
object is not what we're expecting so
the data and activity properties do not
exist so is there any way for us to get
access to the result of the request and
run code when it returns well thankfully
yes because javascript gives us a couple
of ways to wait until a task is finished
and use the result or catch any errors
that occur the first way is by using a
couple of special methods on the promise
object the first one is called then then
is called when the task completes as a
parameter it receives the result of the
task and the catch method is called if
anything goes wrong while processing our
request and this receives the error that
occurred as a parameter
so let's replace this code use the axios
request library and call the get method
now because get returns a promise object
we can immediately chain on the then
method inside our then method we'll log
out to the console the suggested
activity from the api then after this we
can chain on the catch method this will
be called if anything goes wrong while
processing our request let's just log
out to the console the error message
that is returned then we can run this
and see that our console log executes in
the right place
now to simulate an error occurring in
our request let's replace the url with a
call to the http status api this is
really useful for testing different
status codes and we'll just request a
404 not found error we can run this
again and see that our error is neatly
caught by our catch method and printed
out to the console it's worth noting
that any code placed after this promised
chain will be executed immediately so if
we put a console log here at the bottom
we'd expect it to be written out after
our request returns but actually it gets
printed out first this is because only
the code inside the then and catch
methods is executed after the request
returns
now this works fine however as you can
see the code isn't particularly nice to
look at and if you had a lot of
complicated code inside your methods
things would soon start to get quite
unwieldy so what we need really is a way
of receiving the results of our promises
sequentially just as if we were dealing
with simple types like strings and
numbers and this is where the await
keyword comes in and await does exactly
what it says it allows us to wait until
the promise has completed before moving
on to the next line this makes our code
a lot neater and easier to read
javascript requires our await keywords
be used inside functions marked with the
async keyword so let's replace our
promise chain with a function marked
with the async keyword let's call it
getactivity and now we're going to make
the same request to our board api but
notice we have the await keyword before
the method call and immediately after on
our next line of code we can use the
response and log out to the console the
suggested activity this console logline
will not run until the promise resolves
or is returned we can call our get
activity and we'll see that our code
executes perfectly
now because the awake keyword allows us
to move this kind of asynchronous code
back into the main flow of our app we
don't have access to this specialized
catch method to handle any errors that
occur so what happens if something goes
wrong well because our code executes
sequentially we can just wrap this with
a normal try catch block inside our
catch method we can just log out to the
console the error less time to simulate
a server error we'll use the http status
api again and this time we'll request a
500 server error we'll call our get
activity
notice our request error has been nicely
caught and logged out to the console i
hope that has helped to demystify using
promises and the async and await
keywords in javascript if you enjoy this
kind of content then we make videos
every week so make sure to subscribe and
ring that bell icon so you never miss
out on one of our videos thank you so
much for watching and we'll see you next
time
[Music]
関連動画をさらに表示
Asynchronous JavaScript in ~10 Minutes - Callbacks, Promises, and Async/Await
Asynchrony: Under the Hood - Shelley Vohr - JSConf EU
JavaScript Visualized - Promise Execution
Handling Errors | Lecture 144 | React.JS 🔥
#68 What is an Observable | Understanding Observables & RxJS | A Complete Angular Course
How to use escaping closures in Swift | Continued Learning #20
5.0 / 5 (0 votes)