mcabreradev
9/22/2017 - 7:43 AM

Demo Promesas

Demo Promesas

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));
const promesa = fetch('https://swapi.co/api/people/1');

promesa
  .then(res => console.log(res.json()))
  .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'));
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'));
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));