ISA Lecture Week 5 - Asynchronous JavaScript and API PDF
Document Details
Uploaded by FormidableGyrolite3794
Herald College
Kathmandu
Tags
Summary
This document covers asynchronous JavaScript concepts, including callback functions, promises, and the fetch method, which are frequently used in APIs, and is suitable for an introductory computer science course.
Full Transcript
ISA Lecture Week 5 Asynchronous JavaScript and API Previous week Arrow Function Anonymous Function IIFE (Immediately Invoked Function Expression) Higher Order Function Map Reduce Filter ForEach Iteration HTML DOM Virtual DOM JavaSc...
ISA Lecture Week 5 Asynchronous JavaScript and API Previous week Arrow Function Anonymous Function IIFE (Immediately Invoked Function Expression) Higher Order Function Map Reduce Filter ForEach Iteration HTML DOM Virtual DOM JavaScript Selectors Exploring JavaScript Events and event handlers This week’s agenda Understanding Asynchronous Scripting Callback functions and Callback Hell JavaScript Promises Fetch Method Axios 4 4. Asynchronous JavaScript… 4. Asynchronous JavaScript… JavaScript is a single-threaded programming language, which means only one thing can happen at a time. JavaScript engine can only process one statement at a time in a single thread. While single-threaded languages simplify writing codes because you don’t have to worry about the concurrency issues, this also means you cannot perform long operations such as network access without blocking the main thread. A good example of this happening is the window alert function alert("Hello World") 4. Asynchronous JavaScript… Using Asynchronous JavaScript (AJAX, Callback, Promises, async-await), you can perform long network requests without blocking the main thread. Let's take an example of a synchronous programming in JavaScript: 4. Asynchronous JavaScript… From the above example, the console will log, “Hi There!”, “Hello There!” and “The End!” sequentially. As you can see, JavaScript logs the later statements only after the above statement is completed. Now, let's take a look at how a basic asynchronous programming works. We will use a setTimeout() function to achieve that. Remember this function is not a JavaScript function but rather a Web API (browser-function). 4. Asynchronous JavaScript… Now, if you try this code in your browser, this will log “Hi There!”, “The End!” and then wait 2 seconds to log “Hello There!”. This way the code worked on two different thread without blocking the main thread. 4. Asynchronous JavaScript… Although setTimeout() is not the best way to achieve all asynchronous programming, but is enough to help you understand how asynchronous JavaScript works. We will now move more into the asynchronous JavaScript. Lets have a look at Ajax, Callback functions and Promises. 5. Callback Functions… A callback function is a function that is passed as an argument to another function, to be “called back” at a later time. A callback function can either be a general function or an anonymous function. Callback functions are great way to handle something after something else has been completed. By something here we mean a function execution. If we want to execute a function right after the return of some other function, then callback can be used. 5. Callback Functions… Example: We have taken two functions: greet and sayGoodbye. The greet takes two parameters:name(String) and callback(a function).It logs a greeting message using the provided name and then calls the callback function. When we call greet(“Kendall”, sayGoodbye), it will output: 5. Callback Functions For JavaScript to know when an asynchronous operation has a result, it points to a function that will be executed once the result is ready. That function is called a callback function. Here the result can either be the data or an error that occurred during the process. 5. Callback Functions… Here is a simple example of callback function. 5. Callback Functions… Example: The asyncOperation function uses setTimeOut to stimulate asynchronous task. The callback is executed after a delay of 1 second. Output: 5.1. Callback Functions: Callback Hell… Callbacks are a good way to declare what will happen once an I/O operation has a result, but what if you want to use that data in order to make another request? You can only handle the result of the request within the callback function provided. 5.1. Callback Functions: Callback Hell… In this example the variable “result” will not have a value when printed to the console at the last line. With it we are unable to continue with our second request. Callback Functions: Callback Hell… To continue with our second request, we need to create another callback function inside our previous callback function. This will make our code messy to read and very difficult to understand. With that pattern, it means we need to check for errors in every callback. Which just adds to the mess when dealing with multiple requests and callbacks. This anti-pattern is what we call Callback Hell. 5.1. Callback Functions: Callback Hell 18 5.1. Callback Functions: Callback Hell We nested and called the Callback inside the setTimeout() method. The Callback will execute all calls to the print() function in its specified time. Here, we can see the complexity of calling the Callback method in a nesting method. The code becomes difficult to comprehend and debug. Output: 6. JavaScript Promises… A promise is an object that wraps an asynchronous operation and notifies when its done. They are easy to manage when dealing with multiple asynchronous operations where callbacks can create callback hell leading to unmanageable codes. Promises are the ideal choice for handling asynchronous operations in the simplest manner. They can handle multiple asynchronous operations easily and provide better error handling than callbacks. Promise always returns a response. 6. JavaScript Promises… Instead of providing a callback, promises has its own method which you call to tell the promise what will happen if it is successful or when it fails. The methods a promise provides are “then(…)” for when a successful result is available and “catch(…)” for when something went wrong. The next example uses the native Promises as introduced in ES6. 6. JavaScript Promises… A side note here, variable “promise” itself is not a promise but a function that returns a promise. 7. Fetch Method… It is a promise-based interface for fetching resources by making HTTP requests to servers from web browser. It is better and more powerful than XML HTTP requests. Fetch API comes with a fetch() method that allows you to fetch data making an HTTP request i.e. a GET request(getting data) or POST request(for posting data). Fetch method syntax: 7. Fetch Method… In this fetch method, API endpoint is passed as an argument which provides access to a single product. Calling this fetch() method returns a special JavaScript object called promise. We have chained the fetch method with a then() method to investigate the Response object we got from the API call. 7. Fetch Method… The Response object is assigned to a response variable. (You can give the Output: Response object any variable name of choice, res or response is the convention) Use the json() method to view the complete content of the fetched resource ( For instance res.json() or response.json() depending on how you named your variable) The output will be an Object containing some dummy product data- title,description,price,etc. 7. Fetch Method… Handling the status code of the response An HTTP status code is a server response to a browser’s request. The server responds it to the browser’s request with a three-digit code and a status text. A successful response will give a status code of 200 and a status text of OK. If the requested URL throws a server error, the status code will be 500. If the requested resource does not exist, the status code will 400 and status text will be Not found. 7. Fetch Method… Example: status code 200 29 What is Web API? API stands for Application Programming Interface. A Web API is an application programming interface for the Web. A Browser API can extend the functionality of a web browser. A Server API can extend the functionality of a web server. 30 Browser APIs All browsers have a set of built-in Web APIs to support complex operations, and to help accessing data. For example, the Geolocation API can return the coordinates of where the browser is located. 31 Third Party APIs Third party APIs are not built into your browser. To use these APIs, you will have to download the code from the Web. Examples: YouTube API - Allows you to display videos on a web site. Twitter API - Allows you to display Tweets on a web site. Facebook API - Allows you to display Facebook info on a web site. 32 Working with APIs in JavaScript An API is simply a medium to fetch or send data between interfaces. Let’s say you want to make an application that provides the user with some real-time data fetched from the server or maybe even allows you to modify or add data to some other endpoint. This is made possible by the API or the Application Programming Interface. 33 Working with APIs in JavaScript 34 Any Questions 35 36 What is JSON? JSON stands for JavaScript Object Notation JSON is a text format for storing and transporting data JSON is "self-describing" and easy to understand JSON is often used when data is sent from a server to a web page The JSON format is syntactically identical to the code for creating JavaScript objects. Because of this similarity, a JavaScript program can easily convert JSON data into native JavaScript objects. The JSON syntax is derived from JavaScript object notation syntax, but the JSON format is text only. Code for reading and generating JSON data can be written in any programming language. 37 JSON structure JSON is a string whose format very much resembles JavaScript object literal format You can include the same basic data types inside JSON as you can in a standard JavaScript object strings, numbers, arrays, booleans, and other object literals 38 JSON syntax Data is in name/value pairs Data is separated by commas Curly braces hold objects Square brackets hold arrays 39 Why Use JSON? The JSON format is syntactically similar to the code for creating JavaScript objects. Because of this, a JavaScript program can easily convert JSON data into JavaScript objects. Since the format is text only, JSON data can easily be sent between computers, and used by any programming language. JavaScript has a built in function for converting JSON strings into JavaScript objects: JSON.parse() JavaScript also has a built in function for converting an object 40 into a JSON string: JSON.stringify() 41 JSON Data JSON data consists of key/value pairs similar to JavaScript object properties. The key and values are written in double quotes separated by a colon :. For example, // JSON data "name": "John" Note: JSON data requires double quotes for the key. 42 JSON Object The JSON object is written inside curly braces { }. JSON objects can contain multiple key/value pairs. For example, // JSON object { "name": "John", "age": 22 } 43 JSON Array JSON array is written inside square brackets [ ]. For example, // JSON array [ "apple", "mango", "banana"] // JSON array containing objects [ { "name": "John", "age": 22 }, { "name": "Peter", "age": 20 }. 44 { "name": "Mark", "age": 23 } ] Accessing JSON Data You can access JSON data using the dot notation. For example, 45 JavaScript Objects VS JSON Though the syntax of JSON is similar to the JavaScript object, JSON is different from JavaScript objects. 46 Before you come for Lab, Research!! Working with APIs in JavaScript - GeeksforGeeks Web APIs (w3schools.com) JSON Introduction (w3schools.com) JSON Working with JSON - Learn web development | MDN (mozilla.org) 47 9. Before you come for Lab, Research!! HTML DOM Events HTML DOM Elements JavaScript Promise All about Promise