Introduction to Requests with ES6
A promise is an object that handles asynchronous data. A promise has three states:
- pending : when a promise is created or waiting for data.
- fulfilled : the asynchronous operation was handled successfully.
- rejected : the asynchronous operation was unsuccessful.
The first type of requests we’re going to tackle are GET requests using
fetch()
The
fetch()
function:
~Creates a request object that contains relevant information that an API needs.
~Returns a promise that ultimately resolves to a response object, which contains the status of the promise with information the API sent back.
EXAMPLE:
call the fetch()
function and pass it this URL as a string.
Chain a .then()
method to the end of the fetch()
function and pass it the success callback arrow function as its first argument.
We are going to walk through and recreate the boilerplate code necessary to create a GET request using the async
and await
.
key points to keep in mind as we walk through the code:
- Using an
async
function that will return a promise.
await
can only be used in an async
function. await
allows a program to run while waiting for a promise to resolve.
- In a
try...catch
statement, code in the try
block will be run and in the event of an exception/error, the code in the catch
statement will run.
REVIEW:
-
GET and POST requests can be created a variety of ways.
-
Use AJAX to asynchronously request data from APIs.
fetch()
and async
/await
are new functionalities developed in ES6 (promises) and ES8 respectively.
-
Promises are a new type of JavaScript object that represent data that will eventually be returned from a request.
-
fetch()
is a web API that can be used to create requests. fetch()
will return promises.
-
We can chain
.then()
methods to handle promises returned by fetch()
.
-
The
.json()
method converts a returned promise to a JSON object.
-
async
is a keyword that is used to create functions that will return promises.
-
await
is a keyword that is used to tell a program to continue moving through the message queue while a promise resolves.
-
await
can only be used within functions declared with async
.
What I learned today?
I learned an advanced version of the requests in JavaScript by using the ES6.
What I'll be doing tomorrow?
I'll be moving onto a new language which is the SQL.
No comments:
Post a Comment