JavaScript Events and Promises

JavaScript
 
Events
As we’ve seen, events are used to handle
meaningful things that took place in the
document
Element has received focus
Button was clicked
Key was pressed
The document has finished loading
Etc. (see 
https://developer.mozilla.org/en-
US/docs/Web/Events
 for more)
Events Limitation
Look at the following code:
What happens if the image has already
finished loading?
Events Limitation(2)
What if we want to know if multiple images
had finished loading?
The Solution: Promise
When dealing with asynchronous
success/failure, events are less natural
Ideally, we would want something like that:
A promise is an object which supports this
structure
Promise(2)
Main differences between promise and event
handler:
A promise can fail or succeed once
A success/fail callback will be called even if
defined after the event took place
Promises were implemented in many JS
libraries (e.g. Q, when)
Starting from ES6, JavaScript supports
Promises natively
Example: HTTP Get Request
We wish to implement a get request with the
promise syntax
It is meant for demonstration only!
There are many libraries which implement it, and
a native fetch() method – use them!
Example: HTTP Get Request(2)
function get(url) {
  return new Promise(function(resolve, reject) {
    var req = new XMLHttpRequest();
    req.open('GET', url);
    req.onload = function() {
      if (req.status == 200) {
        resolve(req.response);
      }
      else {
        reject(Error(req.statusText));
      }
    };
    req.onerror = function() {
      reject(Error("Network Error"));
    };
    req.send();
  });
}
//usage: get('http://api.icndb.com/jokes/random‘)
Promise: Usage
Syntax:
Chaining:
Simple data
Additional promise
Promise: Multiple Promises
Back to the original problem, Promise.all
method allows us to wait for all promises to
succeed, or for one of them to fail:
Promise.all([promise1,
promise2]).then(function(results) {
//all succeeded })
It is also possible to wait for all promises to
finish (either successfully or not) using
Promise.allSettled
Promise: Error Handling
The following:
Is a syntactic sugar for:
Falsy Values
There are 7 values which evaluate to false in a
condition: 0, 0n (big int), false, null,
undefined, NaN (number), “” (empty string)
All other values are “truthy”
Using the not operator !, we can retrieve the
associated boolean value: (for a variable x, try
!!x)
What does the following instruction do?
name = name || “unknown”
var vs. let
As we’ve seen, variables are declared using
“var” keyword
EC6 has introduces better ways to declare a
variable: let (for a regular variable) and const
(for constant values)
The scope of “let” defined variables is the scope in
which they were defined (inside the { } brackets)
You cannot use the variable before it was defined
var vs. let (Example)
//don’t be afraid! It only meant to show that “var” scoping
can be confusing…
var funcs = [];
for (var i = 0; i < 3; i++) {
  funcs[i] = function() {
    console.log("My value: " + i);
  };
}
for (var j = 0; j < 3; j++) {
  funcs[j]();
}
Slide Note
Embed
Share

JavaScript events are crucial for handling user interactions and document changes, while promises provide a more structured way to deal with asynchronous operations. Learn about the differences between events and promises, how to use them effectively, and see examples of implementing HTTP requests using promises.

  • JavaScript
  • Events
  • Promises
  • Asynchronous Operations

Uploaded on Sep 22, 2024 | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. Download presentation by click this link. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

E N D

Presentation Transcript


  1. JavaScript

  2. Events As we ve seen, events are used to handle meaningful things that took place in the document Element has received focus Button was clicked Key was pressed The document has finished loading Etc. (see https://developer.mozilla.org/en- US/docs/Web/Events for more)

  3. Events Limitation Look at the following code: What happens if the image has already finished loading?

  4. Events Limitation(2) What if we want to know if multiple images had finished loading?

  5. The Solution: Promise When dealing with asynchronous success/failure, events are less natural Ideally, we would want something like that: A promise is an object which supports this structure

  6. Promise(2) Main differences between promise and event handler: A promise can fail or succeed once A success/fail callback will be called even if defined after the event took place Promises were implemented in many JS libraries (e.g. Q, when) Starting from ES6, JavaScript supports Promises natively

  7. Example: HTTP Get Request We wish to implement a get request with the promise syntax It is meant for demonstration only! There are many libraries which implement it, and a native fetch() method use them!

  8. Example: HTTP Get Request(2) function get(url) { return new Promise(function(resolve, reject) { var req = new XMLHttpRequest(); req.open('GET', url); req.onload = function() { if (req.status == 200) { resolve(req.response); } else { reject(Error(req.statusText)); } }; req.onerror = function() { reject(Error("Network Error")); }; req.send(); }); } //usage: get('http://api.icndb.com/jokes/random )

  9. Promise: Usage Syntax: Chaining: Simple data Additional promise

  10. Promise: Multiple Promises Back to the original problem, Promise.all method allows us to wait for all promises to succeed, or for one of them to fail: Promise.all([promise1, promise2]).then(function(results) { //all succeeded }) It is also possible to wait for all promises to finish (either successfully or not) using Promise.allSettled

  11. Promise: Error Handling The following: Is a syntactic sugar for:

  12. Falsy Values There are 7 values which evaluate to false in a condition: 0, 0n (big int), false, null, undefined, NaN (number), (empty string) All other values are truthy Using the not operator !, we can retrieve the associated boolean value: (for a variable x, try !!x) What does the following instruction do? name = name || unknown

  13. var vs. let As we ve seen, variables are declared using var keyword EC6 has introduces better ways to declare a variable: let (for a regular variable) and const (for constant values) The scope of let defined variables is the scope in which they were defined (inside the { } brackets) You cannot use the variable before it was defined

  14. var vs. let (Example) //don t be afraid! It only meant to show that var scoping can be confusing var funcs = []; for (var i = 0; i < 3; i++) { funcs[i] = function() { console.log("My value: " + i); }; } for (var j = 0; j < 3; j++) { funcs[j](); }

More Related Content

giItT1WQy@!-/#giItT1WQy@!-/#