DEV Community

Cristian Fernando
Cristian Fernando

Posted on • Edited on

1

Paracetamol.js💊| #208: Explica este código JavaScript

Explica este código JavaScript

Dificultad: Avanzado

const getName = (name) => {
  return new Promise ((resolve, reject) => {
    setTimeout(() => {
      resolve(name)
    }, 3000)
  })
}


const getAge = (age) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (age < 18) reject(new Error(`${age} no es valido`))
    }, 2000)
  })
}


const counterFriends = (friends) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(friends.length)
    }, 5000)
  })
}

const getPromises = () => {
  const arr = [
        getName("Pepe"), 
        getAge(15), 
        counterFriends(["Ana", "Roberto", "Juan"])];
  return Promise.race(arr)
    .then((response) => {
      console.log(response)
    })
    .catch(err => console.log(err))
}

getPromises()
Enter fullscreen mode Exit fullscreen mode
  • A. "Pepe"
  • B. ["Pepe", 3]
  • C. Promise { <fullfiled> }
  • D. 15 no es edad valida
  • E. 3

Respuesta en el primer comentario.


Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (1)

Collapse
 
duxtech profile image
Cristian Fernando

Respuesta:

  • D. 15 no es edad valida

Promise.race hace solo una cosa:

  • No le importa si la promesa se resulve o falla, siempre regresará la promesa que tarde menos, osea la que tiene el menor delay.

En nuestro ejemplo, lo único que debemos ver son los delays correspondientes:

  • getName tarda 3s
  • getAge tarda 2s
  • counterFriends tarda 5s

¿Cual de todos es el menor?
Aja! Es getAge, pero regresa una promesa rechazada. No importa, es la primera en acabar de ejectarse, entonces regresamos su mensaje de error: 15 no es edad valida.

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay