Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

198
Vistas
¿Cómo puedo convertir esta función asíncrona en promesa?

Hola, tengo esta función asíncrona que recupera el perfil de usuario y los repositorios a través de la API de github y los devuelve en un objeto.

Y quiero convertir esto en una función basada en promesas usando el encadenamiento de promesas (sin ningún método auxiliar).

 async function getUser(user) { const profileResponse = await fetch(`https://api.github.com/users/${user}`); const profileData = await profileResponse.json(); const repoResponse = await fetch(`https://api.github.com/users/${user}/repos`); const reposData = await repoResponse.json(); // returning an object with profile and data return { profile:profileData, repos:repoData, }; } //Calling the function here. getUser("abufattah").then((res) => console.log(res));

Me las arreglé para hacerlo usando dos funciones auxiliares y el método promise.all().

Pero, ¿cómo puedo lograr lo mismo usando el encadenamiento de promesas sin ninguna función auxiliar?

 //Helper function 1: returns a promise with user profile data. function getUserProfile(user) { return fetch(`https://api.github.com/users/${user}`) .then((res) =>res.json()); } //Helper function 2: returns a promise with user repositories data. function getUserRepos(user) { return fetch(`https://api.github.com/users/${user}/repos?per_page=5&sort=created`) .then((res) => res.json()); } //Main function function getUserWithPromise(user) { return new Promise((resolve) => { let profile = getUserProfile(user); let repos = getUserRepos(user); Promise.all([profile, repos]).then((values) => { resolve({ profile: values[0], repos: values[1] }); }); }); } // calling the function here getUserWithPromise("abufattah").then((res) => console.log(res));
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Puedes:

 //Main function function getUserWithPromise(user) { return Promise.all([ fetch(`https://api.github.com/users/${user}`).then((res) =>res.json()), fetch(`https://api.github.com/users/${user}/repos?per_page=5&sort=created`).then((res) => res.json()) ]).then(([result1, result2]) => ({ profile: result1, repos: result2 })); } // calling the function here getUserWithPromise("abufattah").then((res) => console.log(res));

Cadena:

 function getUserWithPromise(user) { return fetch(`https://api.github.com/users/${user}`) .then((res) => { return fetch(`https://api.github.com/users/${user}/repos?per_page=5&sort=created`).then((fetch2Result) => ([res.json(), fetch2Result.json()])) }).then(([result1, result2]) => ({ profile: result1, repos: result2 })) } // calling the function here getUserWithPromise("abufattah").then((res) => console.log(res));
about 4 years ago · Juan Pablo Isaza Denunciar

0

La transformación de la sintaxis async / await en llamadas .then() es bastante mecánica, especialmente si no involucra ninguna sintaxis de flujo de control (bucles o condicionales):

 function getUser(user) { return fetch(`https://api.github.com/users/${user}`).then(profileResponse => { return profileResponse.json().then(profileData => { return fetch(`https://api.github.com/users/${user}/repos`).then(repoResponse => { return repoResponse.json().then(reposData => { // returning an object with profile and data return { profile:profileData, repos:repoData, }; }); }); }); }); }

Pero no hay una buena razón para escribir código como ese. Si es solo que su entorno de destino no admite async / await , deje que un transpiler haga la transformación.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda