https://www.variablenotfound.com/2012/10/closures-en-javascript-entiendelos-de.html
https://blog.soshace.com/en/interviews/15-common-javascript-questions/
https://www.variablenotfound.com/2012/10/closures-en-javascript-entiendelos-de.html
https://blog.soshace.com/en/interviews/15-common-javascript-questions/
<script>
fetch("https://localhost:44339/api/Alumnoes").then(resp => resp.json())
.then(data => {
for (alumno of data) {
console.log(alumno.id + "-" + alumno.nombre + "-" + alumno.nota);
}
})
let alumno = { nombre: "Firulai", nota: 8 };
let params = {
method: 'POST',
body: JSON.stringify(alumno),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
};
fetch('https://localhost:44339/api/Alumnoes', params)
.then(response => response.json())
.then(json => console.log(json))
alumno = { id: 9, nombre: "Firulai", nota: 6 };
params = {
method: 'PUT',
body: JSON.stringify(alumno),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
};
fetch('https://localhost:44339/api/Alumnoes/9', params)
.then(response => response.json())
.then(json => console.log(json))
.catch(error => console.log(error));
params = {
method: 'DELETE',
headers: {
"Content-type": "application/json; charset=UTF-8"
}
};
fetch('https://localhost:44339/api/Alumnoes/13', params)
.then(response => response.json())
.then(json => console.log(json))
.catch(error => console.log(error));
</script>
En la siguiente url:
https://randomuser.me/api/?results=3
Nos devuelve información aleatoria sobre usuarios.
Vamos a crear una web que al pulsar un botón nos pida por fetch a esa web 3 usuarios y nos muestre su nombre y su foto.
Vamos a crear una función cargar imagen a la que le pasemos una url e intente cargar la imagen, si existe la url y es una imagen que la ponga en un div. Si no hay imagen que ponga un mensaje de imagen no encontrada.
Con promesas.
<script>
fetch('https://deckofcardsapi.com/api/deck/new/shuffle/')
.then(
function (response) {
console.log(response);
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}
// Examine the text in the response
response.json().then(function (data) {
console.log(data);
});
}
)
.catch(function (err) {
console.log('Fetch Error :-S', err);
});
fetch('https://deckofcardsapi.com/api/deck/new/shuffle/')
.then(
function (response) {
return response.json()
// Examine the text in the response
}
).then(function (data) {
console.log(data);
})
.catch(function (err) {
console.log('Fetch Error :-S', err);
});
fetch('https://deckofcardsapi.com/api/deck/new/shuffle/')
.then(response => response.json())
.then(data => console.log(data))
.catch(function (err) {
console.log('Fetch Error :-S', err);
});
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
body: JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1
}),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
})
.then(response => response.json())
.then(json => console.log(json))
let data = {
title: 'foo',
body: 'bar',
userId: 1
};
let params = {
method: 'POST',
body: JSON.stringify(data),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
};
fetch('https://jsonplaceholder.typicode.com/posts',params)
.then(response => response.json())
.then(json => console.log(json))
</script>
const apuestas = new Promise((resolve, reject) => {
let total = 0;
let veces = 10000;
for (let i = 0; i < veces; i++) {
for (let j = 0; j < veces; j++) {
total += Math.random() * 10;
}
}
console.log(total);
total = total / (veces ** 2);
if (total >= 5) {
let win = 'Hemos ganado';
resolve(win);
} else {
let loose = 'Hemos perdido';
reject(loose);
}
})
apuestas.then((result)=>{
console.log(result);
}).catch((error)=>{
console.log(error);
})
console.log("Fin programa");
Enlaces:
https://developers.google.com/web/fundamentals/primers/promises?hl=es
https://scotch.io/tutorials/javascript-promises-for-dummies
https://www.codingame.com/playgrounds/347/javascript-promises-mastering-the-asynchronous/your-first-code-with-promises
https://flaviocopes.com/javascript-promises/
https://exploringjs.com/es6/ch_promises.html#sec_examples-promises
let pagaExtra = false;
// Generación de la promesa
let nuevoTelefono = new Promise(
function (resolve, reject) {
if (pagaExtra) {
var telefono = {
marca: 'Samsung',
color: 'black'
};
resolve(telefono); // fulfilled
} else {
var razon = new Error('Sin paga extra');
reject(razon); // reject
}
}
);
//Consumir la promesa
let comprar=function(){
nuevoTelefono.then(
//La promesa se ha cumplido
function(fulfilled){
console.log(fulfilled);
}
).catch(
//La promesa no se ha cumplido
function(error){
console.log(error);
}
)
}
comprar();
Añadimos console.log:
let pagaExtra = true;
// Generación de la promesa
let nuevoTelefono = new Promise(
function (resolve, reject) {
if (pagaExtra) {
var telefono = {
marca: 'Samsung',
color: 'black'
};
resolve(telefono); // fulfilled
} else {
var razon = new Error('Sin paga extra');
reject(razon); // reject
}
}
);
//Consumir la promesa
let comprar=function(){
console.log("inicio");
nuevoTelefono.then(
//La promesa se ha cumplido
function(fulfilled){
console.log(fulfilled);
}
).catch(
//La promesa no se ha cumplido
function(error){
console.log(error);
}
)
console.log("fin");
}
comprar();
Resultado:
inicio
fin
{marca: «Samsung», color: «black»}
Con parámetros:
let comprar = function (pagaExtra) {
let nuevoTelefono = new Promise(
function (resolve, reject) {
if (pagaExtra) {
var telefono = {
marca: 'Samsung',
color: 'black'
};
resolve(telefono); // fulfilled
} else {
var razon = new Error('Sin paga extra');
reject(razon); // reject
}
}
);
nuevoTelefono.then(
//La promesa se ha cumplido
function (fulfilled) {
console.log(fulfilled);
}
).catch(
//La promesa no se ha cumplido
function (error) {
console.log(error);
}
)
}
comprar(true);
comprar(false);