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));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));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.