Skip to content

Instantly share code, notes, and snippets.

@mcabreradev
Last active September 22, 2017 07:48
Show Gist options
  • Save mcabreradev/13f75ec1c4d98d7257876f32dacae44d to your computer and use it in GitHub Desktop.
Save mcabreradev/13f75ec1c4d98d7257876f32dacae44d to your computer and use it in GitHub Desktop.
Demo Promesas
const fruits = ['apple', 'peach', 'lime', 'watermelon']; // Array de frutas
function getFruit(fruit) {
return new Promise((resolve, reject) => { // Se crea la promesa con los 2 parámetros
// Se busca en el array si existe la fruta
if (fruits.find(item => item === fruit)) {
resolve(`${fruit} was found!`); // Se resuelve la promesa
} else {
reject(Error('no fruit was found!')); // Se rechaza la promesa
}
});
}
// Consultar si existe apple dentro del array de frutas
getFruit('apple')
.then(res => console.log(res)) // si es exitoso
.catch(err => console.error(err)) // si hay algun error
// Consultar si existe orange dentro del array de frutas
getFruit('orange')
.then(res => console.log(res))
.catch(err => console.error(err));
function hydrateHomeworld(res) {
fetch(res.homeworld)
.then(planet => planet.json())
.then(planet => res.homeworld = planet);
return res;
}
function getPeople(id) {
return fetch('https://swapi.co/api/people/' + id);
}
getPeople(1)
.then(res => res.json())
.then(res => hydrateHomeworld(res))
.then(res => console.log(res))
.catch(err => console.error('Error al consultar api'));
function hydrate(res, type) {
let aux = [];
res[type].map(film => {
fetch(film)
.then(res => res.json())
.then(res => aux.push(res));
});
res[type] = aux;
return res;
}
function hydrateHomeworld(res) {
fetch(res.homeworld)
.then(planet => planet.json())
.then(planet => res.homeworld = planet);
return res;
}
function getPeople(id) {
return fetch('https://swapi.co/api/people/' + id);
}
getPeople(1)
.then(res => res.json())
.then(res => hydrateHomeworld(res))
.then(res => hydrate(res, 'films'))
.then(res => hydrate(res, 'species'))
.then(res => hydrate(res, 'starships'))
.then(res => hydrate(res, 'vehicles'))
.then(res => console.log(res))
.catch(err => console.error('Error al consultar api'));
const promesa = fetch('https://swapi.co/api/people/1');
promesa
.then(res => console.log(res.json()))
.catch(err => console.error('Error al consultar api'))
const weather = new Promise( (resolve, reject) => {
setTimeout(() => {
resolve({ temp: 29, conditions: 'Soleado con nubes'});
}, 2000);
});
weather
.then(response => console.log(response))
.catch(error => console.error(error));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment