9.) Async JavaScript and HTTP Requests

¡Supera tus tareas y exámenes ahora con Quizwiz!

Consuming Promises

"I have a promise, when it settles, then here's what I want to happen..." The .then() method of a JavaScript Promise object can be used to get the eventual result (or error) of the asynchronous operation. .then() accepts two function arguments. The first handler supplied to it will be called if the promise is resolved. The second one will be called if the promise is rejected. const promise = new Promise((resolve, reject) => { setTimeout(() => { resolve('Result'); }, 200); }); promise.then((res) => { console.log(res); }, (err) => { alert(err); });

Handling a POST Request

.then((response) => { if(response.ok) { return response.json() } throw new Error('Request failed!')

Handling Independent Promises

async function waiting() { const firstValue = await firstAsyncThing(); const secondValue = await secondAsyncThing(); console.log(firstValue, secondValue);} async function concurrent() { const firstPromise = firstAsyncThing(); const secondPromise = secondAsyncThing();console.log(await firstPromise, await secondPromise);}

Asynchronous Code

asynchronous code can be executed in parallel to other code that is already running. Without the need to wait for other code to finish before executing, our apps can save time and be more efficient. This type of behavior is considered non-blocking.

async GET Requests

const getSuggestions = async () => { const wordQuery = inputField.value; const endpoint = `${url}${queryParams}${wordQuery}`; try{ const response = await fetch(endpoint, {cache: 'no-cache'}); if(response.ok){ const jsonResponse = await response.json() } } catch(error){ console.log(error) } }

Asynchronous callbacks

executes after a specific condition is met and runs concurrently to any other code currently running -addEventListener() -setTimeout() -setInterval()

REVIEW: REQUESTS WITH FETCH API

-GET and POST requests can be created in a variety of ways. -We can use fetch() and async/await to asynchronous request data from APIs. -Promises are a type of JavaScript object that represents data that will eventually be returned from a request. -The fetch() function can be used to create requests and will return promises. -We can chain .then() methods to handle promises returned by the fetch() function. -The async keyword is used to create asynchronous functions that will return promises. -The await keyword can only be used with functions declared with the async keyword. -The await keyword suspends the program while waiting for a promise to resolve.

REVIEW: JAVASCRIPT PROMISES

-Promises are JavaScript objects that represent the eventual result of an asynchronous operation. -Promises can be in one of three states: pending, resolved, or rejected. -A promise is settled if it is either resolved or rejected. -We construct a promise by using the new keyword and passing an executor function to the Promise constructor method. setTimeout() is a Node function which delays the execution of a callback function using the event-loop. -We use .then() with a success handler callback containing the logic for what should happen if a promise resolves. -We use .catch() with a failure handler callback containing the logic for what should happen if a promise rejects. -Promise composition enables us to write complex, asynchronous code that's still readable. We do this by chaining multiple .then()'s and .catch()'s. -To use promise composition correctly, we have to remember to return promises constructed within a .then(). -We should chain multiple promises rather than nesting them. To take advantage of concurrency, we can use Promise.all().

HTTP & TCP: How it Works

-When you type an address such as www.codecademy.com into your browser, you are commanding it to open a TCP channel to the server that responds to that URL (or Uniform Resource Locator). A URL is like your home address or phone number because it describes how to reach you. Once the TCP connection is established, the client sends a HTTP GET request to the server to retrieve the webpage it should display. After the server has sent the response, it closes the TCP connection. If you open the website in your browser again, or if your browser automatically requests something from the server, a new connection is opened which follows the same process described above.

REVIEW: ASYNC AWAIT

-async...await is syntactic sugar built on native JavaScript promises and generators. -We declare an async function with the keyword async. -Inside an async function we use the await operator to pause execution of our function until an asynchronous action completes and the awaited promise is no longer pending . await returns the resolved value of the awaited promise. -We can write multiple await statements to produce code that reads like synchronous code. -We use try...catch statements within our async functions for error handling. -We should still take advantage of concurrency by writing async functions that allow asynchronous actions to happen in concurrently whenever possible.

The Event Loop steps

1.)The JavaScript engine maintains a call stack, which is used to keep track of the currently executing function. 2.)When an asynchronous task is initiated, such as a timer or an HTTP request, it is added to a queue. 3.) When the call stack is empty, the event loop checks the queue for any tasks that have completed. 4.)If a completed task is found, its associated callback function is added to the call stack and executed. 5.)This process continues, with tasks being added to the queue and executed as they complete, until the program finishes executing.

Constructing a Promise Object

An instance of a JavaScript Promise object is created using the new keyword. The constructor of the Promise object takes a function, known as the executor function, as the argument. This function is responsible for resolving or rejecting the promise. const executorFunction = (resolve, reject) => { if (someCondition) { resolve('I resolved!'); } else { reject('I rejected!'); }} const myFirstPromise = new Promise(executorFunction);

API

An Application Programming Interface (API) is a software tool that makes it easier for developers to interact with another application to use some of that application's functionality. Like tools in the physical world, APIs are built to solve specific, repeated, and potentially complex problems. an API is a way for different software applications to communicate and share data with each other. It allows developers to access and use specific functions and data from a service or platform without needing to know how the service or platform is implemented internally

Event Loop

At a high level, the event loop is a system for managing code execution The event loop is made up of these parts: -Memory Heap -Call Stack -Event Queue -Event Loop -Node or Web APIs The Heap The heap is a block of memory where we store objects in an unordered manner. JavaScript variables and objects that are currently in use are stored in the heap. The Call Stack The stack, or call stack, tracks what function is currently being run in your code. When you invoke a function, a frame is added to the stack. Frames connect that function's arguments and local variables from the heap. Frames enter the stack in a last in, first out (LIFO) order The Event Queue The event queue is a list of messages corresponding to functions that are waiting to be processed.No code is executed in the event queue; instead, it holds functions that are waiting to be added back into the stack. The Event Loop This event loop is a specific part of our overall event loop concept. Messages that are waiting in the event queue to be added back into the stack are added back via the event loop. When the call stack is empty, if there is anything in the event queue, the event loop can add those one at a time to the stack for execution. First the event loop will poll the stack to see if it is empty. It will add the first waiting message. It will repeat steps 1 and 2 until the stack has cleared.

JSON

JSON stands for "JavaScript Object Notation." It is a popular and standard format that is easy for humans to read and write, and easy for machines to parse and generate. JSON is often used for transmitting data between a web application and a server as an alternative to XML. JSON data is represented as key-value pairs, similar to an object in JavaScript.

Async Await Handling Errors

JavaScript async functions uses try...catch statements for error handling. This method allows shared error handling for synchronous and asynchronous code. async function usingTryCatch() { try { let resolveValue = await asyncFunction('thing that will fail'); let secondValue = await secondAsyncFunction(resolveValue); } catch (err) { // Catches any errors in the try block console.log(err); }} usingTryCatch();

GET Requests using Fetch

The fetch() function: -Creates a request object that contains relevant information that an API needs. -Sends that request object to the API endpoint provided. -Returns a promise that ultimately resolves to a response object, which contains the status of the promise with information the API sent back. fetch('url') .then( response => { console.log(response); }, rejection => { console.error(rejection.message); );

Thread

Generally, the amount of tasks a language can execute is limited by the amount of threads the language has access to. JavaScript is a single-threaded language. However, it can handle asynchronous code using the event loop.

Making a GET Request

HTTP GET requests are made with the intention of retrieving information or data from a source (server) over the web. GET requests have no body, so the information that the source requires, in order to return the proper response, must be included in the request URL path or query string.

POST Requests using Fetch

HTTP POST requests are made with the intention of sending new information to the source (server) that will receive it. For a POST request, the new information is stored in the body of the request.

HTTP

Hypertext Transfer Protocol: used to structure requests and responses over the internet. HTTP requires data to be transferred from one point to another over the network

async-javascript-syntaxes

In JavaScript, asynchronous code can be written in a variety of different ways, including: -Callbacks -Promises -async/await

REST key principles

One of the key principles of REST is statelessness, which means that the server does not store any client context between requests. Instead, each request from the client must contain all the necessary information to complete the request, and the server must respond with all the necessary information to complete the request. RESTful web services use HTTP methods (such as GET, POST, PUT, and DELETE) to perform CRUD (Create, Read, Update, and Delete) operations on resources. For example, GET is used to retrieve a resource, POST is used to create a new resource, PUT is used to update an existing resource, and DELETE is used to delete a resource. Another important principle of REST is the use of hypermedia links to navigate between resources. Hypermedia links are links that provide contextual information about a resource and can be used to navigate to related resources.

Promise Object

Promises are objects that represent the eventual outcome of an asynchronous operation. A Promise object can be in one of three states: Pending: The initial state, the operation has not completed yet Fulfilled: The operation has completed successfully and the promise now has a resolved value Rejected: The operation has failed and the promise has a reason for the failure

REST

REST (Representational State Transfer) is a way to design web services that allows different computer systems to talk to each other over the internet. it's a set of guidelines that help developers create APIs (Application Programming Interfaces) that are easy to understand and use. RESTful APIs typically use HTTP methods like GET, POST, PUT, and DELETE to access and manipulate resources, which are represented as URLs. RESTful APIs also typically use a standard set of response codes (like 200 OK, 404 Not Found, etc.) to communicate the status of a request. Overall, REST is a flexible and widely used architecture for building web services that can be used by a variety of different applications and systems.

Requesting Information from a Third-party API

Rules and Requirements Organizations that maintain third-party APIs often set rules and requirements for how developers can interact with their APIs. For OpenWeather, we need to sign up for an account and generate a special token called an API key that grants our account the ability to make API requests. Making Requests Some of an API's specifications relate to making a request for data. These specifications could include more parameters for specific information or the inclusion of an API key. For example, when using the OpenWeather API, we need to provide more information to search for weather information — such information could include: the name of a city, time of day, the type of forecast, etc. These specifications for making a request can also be found in the API documentation. Response Data After we make a successful API request, the API sends back data. Many APIs format their data using JSON which looks like a JavaScript object. It's then up to us how to determine how to consume, or use, this information in our apps. If we got back that sample JSON above, we could parse out the temperature information and display it on our app.

Using catch() with Promises

Separation of concerns The function passed as the second argument to a .then() method of a promise object is used when the promise is rejected. An alternative to this approach is to use the JavaScript .catch() method of the promise object. The information for the rejection is available to the handler supplied in the .catch() method. prom .then((resolvedValue) => { console.log(resolvedValue); }) .catch((rejectionReason) => { console.log(rejectionReason); });

Chaining Multiple Promises

The .then() method returns a Promise, even if one or both of the handler functions are absent. Because of this, multiple .then() methods can be chained together. This is known as composition. In the code block, a couple of .then() methods are chained together. Each method deals with the resolved value of their respective promises. const promise = new Promise(resolve => setTimeout(() => resolve('dAlan'), 100)); promise.then(res => { return res === 'Alan' ? Promise.resolve('Hey Alan!') : Promise.reject('Who are you?') }).then((res) => { console.log(res) }, (err) => { alert(err) });

The aysnc and await Keywords

The async...await ES6 JavaScript syntax offers a new way to write more readable and scalable code to handle promises. A JavaScript async function can contain statements preceded by an await operator. The operand of await is a promise. At an await expression, the execution of the async function is paused and waits for the operand promise to resolve. The await operator returns the promise's resolved value. An await operand can only be used inside an async function. function helloWorld() { return new Promise(resolve => { setTimeout(() => { resolve('Hello World!'); }, 2000); }); } //ASYNC async function msg() { const msg = await helloWorld(); console.log('Message:', msg); } msg(); // Message: Hello World! <-- after 2 seconds

Concurrency

The concurrency model in JavaScript refers to how the language handles multiple tasks running at the same time. JavaScript is a single-threaded language, which means that it can only execute one task at a time. However, it supports concurrency through the use of asynchronous programming techniques, such as callbacks, promises, and async/await.

Making a POST request

The fetch() function accepts an optional second argument, an options object, used to customize the request. This can be used to change the request type, headers, specify a request body, and much more. In the example code below, the fetch() function as a second argument—an object containing options for the fetch request specifying the method and the body. fetch('https://api-to-call.com/endpoint', { method: 'POST', body: JSON.stringify({id: "200"}) }).then(response => { if(response.ok){ return response.json(); } throw new Error('Request failed!'); }, networkError => { console.log(networkError.message); }).then(jsonResponse => { console.log(jsonResponse); })

Handling Dependent Promises(multiple/chaining)

The true beauty of async...await is when we have a series of asynchronous actions which depend on one another //Promise function nativePromiseVersion() { returnsFirstPromise() .then((firstValue) => { console.log(firstValue); return returnsSecondPromise(firstValue); }) .then((secondValue) => { console.log(secondValue); });} //Async... Await async function asyncAwaitVersion() { let firstValue = await returnsFirstPromise(); console.log(firstValue); let secondValue = await returnsSecondPromise(firstValue); console.log(secondValue);}

!!! Success and Failure Callback Functions

To handle a "successful" promise, or a promise that resolved, we invoke .then() on the promise, passing in a success handler callback function: const prom = new Promise((resolve, reject) => { resolve('Yay!'); }); const handleSuccess = (resolvedValue) => { console.log(resolvedValue);}; prom.then(handleSuccess); // Prints: 'Yay!'

Using Promise.all()

To maximize efficiency we should use concurrency, multiple asynchronous operations happening together. With promises, we can do this with the function Promise.all(). The JavaScript Promise.all() method can be used to execute multiple promises in parallel. The function accepts an array of promises as an argument. If all of the promises in the argument are resolved, the promise returned from Promise.all() will resolve to an array containing the resolved values of all the promises in the order of the initial array. Any rejection from the list of promises will cause the greater promise to be rejected.

Await Promise.all()

When using JavaScript async...await, multiple asynchronous operations can run concurrently. If the resolved value is required for each promise initiated, Promise.all() can be used to retrieve the resolved value, avoiding unnecessary blocking. let promise1 = Promise.resolve(5); let promise2 = 44; let promise3 = new Promise(function(resolve, reject) { setTimeout(resolve, 100, 'foo'); }); Promise.all([promise1, promise2, promise3]).then(function(values) { console.log(values); }); // expected output: Array [5, 44, "foo"]

Handling a GET Request

a then() method is chained to the end of the fetch(). It ends with the response callback to handle success and the rejection callback to handle failure. another .then() method is chained to which will allow us to take the information that was returned with the promise and manipulate the webpage. parsing into JSON

setTimeout()

setTimeout() is an asynchronous JavaScript function that executes a code block or evaluates an expression through a callback function after a delay set in milliseconds.

Synchronous Code

synchronous code executes in sequential order — it starts with the code at the top of the file and executes line by line until it gets to the end of the file. This type of behavior is known as blocking (or blocking code) since each line of code cannot execute until the previous line finishes.

async POST Requests

try { const response = await fetch(url, { method: 'POST', body: data, headers: { 'Content-type': 'application/json', 'apikey': apiKey } } ); if(response.ok){ const jsonResponse = await response.json(); renderResponse(jsonResponse); } } catch (error) { console.log(error); }


Conjuntos de estudio relacionados

algebra 2b - unit 1: lost in translation lessons 1-5

View Set

population health exam 2 (evolve)

View Set

Segundo Parcial- Administración de Desarrollo

View Set