Diferència entre revisions de la pàgina «Promises»

De Wiket
Salta a la navegació Salta a la cerca
Línia 4: Línia 4:
 
=Exercises=
 
=Exercises=
 
<ol>
 
<ol>
 +
<li>
 +
Create a form with 3 fields at the least
 +
<!-- function validateForm(formData) {
 +
  return new Promise(function(resolve, reject) {
 +
    if (formData.username.length < 3) {
 +
      reject(new Error("Username must be at least 3 characters"));
 +
    } else if (!formData.email.includes("@")) {
 +
      reject(new Error("Invalid email address"));
 +
    } else {
 +
      resolve();
 +
    }
 +
  });
 +
}
 +
 +
var formData = {
 +
  username: "johndoe",
 +
  email: "[email protected]"
 +
};
 +
 +
validateForm(formData)
 +
  .then(function() {
 +
    submitForm(formData);
 +
  })
 +
  .catch(function(error) {
 +
    showError(error.message);
 +
  });
 +
-->
 +
</li>
 
<li>Make a web page with a button (button text: Load image), when we click on that button you have use "promises" to load an image from your server and catch the errors, if there are
 
<li>Make a web page with a button (button text: Load image), when we click on that button you have use "promises" to load an image from your server and catch the errors, if there are
 
<!-- function loadImage(url) {
 
<!-- function loadImage(url) {

Revisió del 12:35, 31 gen 2023

volver a M06 Desarrollo web en entorno cliente

Resources

Javascript Promises

Exercises

  1. Create a form with 3 fields at the least
  2. Make a web page with a button (button text: Load image), when we click on that button you have use "promises" to load an image from your server and catch the errors, if there are
  3. With the given code, create a web page that call a server with some data (it's doesn't matter what data) and print the data on the page applying some kind of format.
    const loadJSON = (file) => {
      return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.open('GET', file, true);
        xhr.responseType = 'json';
        xhr.onload = () => {
          if (xhr.status === 200) {
            resolve(xhr.response);
          } else {
            reject(xhr.statusText);
          }
        };
        xhr.onerror = () => reject(xhr.statusText);
        xhr.send();
      });
    };