자바스크립트 S16: Asynchronous JavaScript: Promises, Async/Await and AJAX

소바·2022년 10월 6일
0

자바스크립트

목록 보기
10/13

Asynchoronous JavaScript, AJAX & APIs

자바스크립트 런타임 참고하기

synchronous 코드

Asynchronous 코드

callback함수 ≠ Asynchronous

XML? JSON?

API? Software?

API란?

Software란?

정리하자면(API in general term)

자바스크립트에서의 API

AJAX란?

Our First AJAX Call: XMLHttpRequest

Public APIs 이용하기

public APIs

HTTP Request: 데이터 get하기


How the Web Works: Requests & Responses

Web server에 접근할 때 일어나는 일

Domain name

Now this domain name, restcountries.eu is actually not the real address
of the server that we're trying to access. that is easy for us to memorize.

DNS(=Domain name server)

But what this means is that we need a way of kind of converting the domain name
to the real address of the server.d
And that happens through a so-called D-N-S. So DNS stands for domain name server
and domain name servers are a special kind of server.

So the first step that happens when we access any Web server is that the browser makes a request to a DNS and this special server will then of the URL to the server's real IP addres.

TCP / IP socket

So once we have the real IP address, a TCP socket connection is established between the browser and the server. And so they are now finally connected.

And this connection is typically kept alive for the entire time that it takes
to transfer all files of the Website or all data.

Now what are TCP and IP?
TCP is the Transmission Control Protocol.
And IP is the Internet Protocol And together they are communication protocols.
that define exactly how data travels across the Web. They are basically the Internet's fundamental control system.

TCP

So first the job of TCP is to break the requests and responses down into thousands of small chunks, called packets before they are sent.
Once the small packets arrive at their final destination, TCP will reassemble all the packets into the original request or response.
And this is necessary so that each packet can take a different route through the Internet because this way the message arrives at the destination as quick as possible, which would not be possible if we sent the entire data simply as a big chunk.

IP

the job of the IP protocol is to actually send and route these packets through the Internet. So it ensures that they arrive at the destination they should go,
using IP addresses on each packet.

HTTP REQUEST

And the request that we make is an HTTP request, where HTTP stands for Hypertext Transfer Protocol.
They are the communication protocols that define how data travels across the Web.
Now in the case of HTTP, it's just a protocol that allows clients and Web servers to communicate. And that works by sending requests and response messages from client to server and back.

start line

is not only for getting data, but we can also send data, now right.

HTTP request headers

Then the next part of the request are the request headers, which is just some information that we sent about the request itself.

Request Body

And the main difference between HTTP and HTTPS
is that HTTPS is encrypted using TLS or SSL, which are yet some are protocols,
the logic behind HTTP requests and responses still applies to HTTPS, alright?

Rendering

But anyway, when all the files have finally arrived, then the Web page can be rendered in the browser, according to the HTML, CSS and JavaScript specifications that you already know.

Callback Hell

So they were basically running in parallel.
And we could not control which one finished first,
let's create a sequence of AJAX calls,

And that special name is callback hell.
is when we have a lot of nested callbacks
in order to execute asynchronous tasks in sequence.

Promises & the Fetch API

promise란?

promise = 복권

promise의 이점

promise: life cycle

Consuming Promises

정리: Arrow 함수로

Chaining Promises

Handling Rejected Promises

error 핸들링(catch)하기

finally 메서드

Throwing Errors Manually

throw new Error의 역할

getJSON 함수로 encapsulation 해주기

error 처리작업이 중요한 이유

Asynchornous Behind the Scenes: The Event Loop

Finally, whenever the call stack is empty
the event loop takes callbacks from the callback queue
and puts them into call stack so that they can be executed.
So the event loop is the essential
piece that makes asynchronous behavior possible
in JavaScript.

It's the reason why we can have a
non blocking concurrency model in JavaScript.
And a concurrency(동시실행) model is simply how a language handles
multiple things happening at the same time.
non blocking concurrency actually work?
And why is the event loop so important?

runtime

And let's focus on the essential parts of the runtime here.
So, as you know, by now, a JavaScript engine is built

Okay, but now let's start by selecting this image element.
And then in the next line
we set the source attribute of that image to dog.jpg.
And as we learned before this will now start to load
this image asynchronously in the background.
So, as you already know everything related to the DOM
is not really part of JavaScript, but of the web APIs.
So, again, these asynchronous tasks will all run
in the web API environment of the browser.

Now, if the image would be loading in a synchronous way
it would be doing so right in the call stack
blocking the execution of the rest of the code.
So it does not happen in the call stack.
So, not in the main thread of execution,
but really in the web APIs environment

이벤트 리스너

Now, if we want to do something after the image
has finished loading,
then we need to listen to the load event.
So, here we attach an event listener
to the load event of that image
and pass an a callback function as always.
In practice, this means to register this callback
in the web APIs environment,
exactly where the image is loading.
And to callback will stay there
until the load event is emitted(discharged).
So, we're handling asynchronous behavior here
with a callback just as we learned before,

AJAX call

And so, in the next line, we make an AJAX call using the fetch API.
And as always the asynchronous fetch operation will happen
in the web APIs environment.
And again, that's because otherwise we would be blocking
the call stack and create a huge lag in our application.

then

Finally, we use the then method on the promise returned
by the fetch function.
And this will also register a callback
in the web API environment so that we can react
to the future resolved value of the promise.
So this callback is associated with a promise
that is fetching the data from the API.

So, with this, we have now executed all the
top level of code.
So, all the code that is not inside any callback function
in asynchronous way.
We also have the image loading in the background
and some data being fetched from an API.

image callback queue

Let's say the image has finished loading
and therefore the load event is emitted on that image.
What happens next,
is that the callback for this event is put
into callback queue.
And the callback queue is basically an ordered list
of all the callback functions that are
in line to be executed.
And you can think of this callback queue,
as a to do list that you would write
for yourself with all the tasks that you have to complete.

So, imagine that you set a timer for five seconds.
And so after five seconds that timer's callback will be put
on the callback queue, right.
to run all the other callbacks that were already waiting
in line in front of your timer.

So, what this means is that the timers duration that you define is not a guarantee.
The only guarantee is that the timers callback
will not run before five seconds,
but it might very well run after five seconds have passed.
So, it all depends on the state of the callback queue.
And also another queue that we're gonna learn about

Now, another thing that's important to mention here is that the callback queue also contains callbacks coming
from DOM events like clicks or key presses or whatever.
Now, we learned before that DOM events are not really
asynchronous behavior, but they still use the
callback queue to run their attached callbacks.
So, if a click happens on a button with addEventListener
then what will happen is just like what I illustrated here
with the asynchronous load event.

event loop

It looks into the call stack and determines whether
it's empty or not.
Except of course for the global context,
then if the stack is indeed empty
which means that there's currently no code being executed
then it will take the first callback from the callback queue
and put it on the call stack two will be executed.
And this is called an event loop tick.
So each time the event loop takes a callback
from the callback queue.
We say that there was an event loop tick.
So, the event loop is basically who decides exactly
when each callback is executed.
We can also say that the event loop does the orchestration
of this entire JavaScript runtime.

Another thing that becomes clear from this whole explanation
is that the JavaScript language itself has actually
no sense of time.
That's because everything that is asynchronous
does not happen in the engine.
It's the runtime who manages all the asynchronous behavior.
And it's the event loop who decides
which code will be executed next.
But the engine itself simply executes
whatever code it has given.

fetch data

but we're not done yet.
Because we still have to fetch function
getting data from the AJAX call in the background.
And this is basically happening with a promise.
Remember, now with promises things work in a slightly
different way which is why I included this promise example
So, let's say that the data has now finally arrived.
And so the fetch is done.
Now, callbacks related to promises
like this one that we registered with the
promises then method.
Do actually not go into the callback queue.
So, again this callback did we still have here,
which is coming from a promise will not be moved into the
callback queue.
Instead, callbacks of promises have a special queue
for themselves, which is the so called microtasks queue.
Now, what is special about the microtasks queue is
that it basically has priority over the callback queue.
So, at the end of an event loop tick,
so after a callback has been taken
from the callback queue, the event loop will check
if there are any callbacks in the microtasks queue.
And if there are, it will run all of them
before it will run any more callbacks
from the regular callback queue.
And, by the way, we call these callbacks
from promises microtasks.
And therefore the name microtasks queue.

currently, we actually do have a microtask sitting
in a microtasks queue, the call stack is also empty.
And therefore the event loop will now take this callback
and put it in the call stack just like it does with
callbacks from the callback queue.
And it doesn't matter if the callback queue is empty or not.
And again, that's because microtasks always have priority.
In practice, this means that microtasks can basically
cut in line before all other regular callbacks.
Now, if one microtask adds a new microtask
then that new microtask is also executed
before any callbacks from the callback queue.
And this means that the microtasks queue
can essentially starve the callback queue.
Because if we keep adding more and more microtasks,
then callbacks in the callback queue can never execute.
The only difference is that they go into different queues
and that the event loop gives microtasks priority
over regular callbacks.

Building a Simple Promise

promise 생성자함수 & executor함수

promise cusuming하기 : resolved promise & rejected promise

asynchronous behavior encapsulation

promisifying

Consuming Promises with async / await

await VS. then

Error Handling with try...catch

Returning Values from Async Functions

Running Promises in parallel

profile
소바보이

0개의 댓글