Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

197
Views
¿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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!