Diferència entre revisions de la pàgina «Promises»
Salta a la navegació
Salta a la cerca
Línia 4: | Línia 4: | ||
=Exercises= | =Exercises= | ||
<ol> | <ol> | ||
+ | <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) { | ||
+ | return new Promise(function(resolve, reject) { | ||
+ | var image = new Image(); | ||
+ | image.onload = function() { | ||
+ | resolve(image); | ||
+ | }; | ||
+ | image.onerror = function() { | ||
+ | reject(new Error("Could not load image at " + url)); | ||
+ | }; | ||
+ | image.src = url; | ||
+ | }); | ||
+ | } | ||
+ | |||
+ | loadImage("https://example.com/image.jpg") | ||
+ | .then(function(image) { | ||
+ | document.body.appendChild(image); | ||
+ | }) | ||
+ | .catch(function(error) { | ||
+ | console.error(error); | ||
+ | }); | ||
+ | --></li> | ||
<li>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. | <li>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. | ||
<pre class="prettyprint"> | <pre class="prettyprint"> |
Revisió del 12:27, 31 gen 2023
volver a M06 Desarrollo web en entorno cliente
Resources
Exercises
- 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
- 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(); }); };