Encontré diferentes soluciones aquí, pero ninguna funcionó para mí. Tengo este código simple:
const Element = () => { async function getEndData() { const data = (await getEnd()); return data; } } const getEnd = async () => { return await axios.get('http://localhost:8080/end').then(res => res.data); } Y siempre devuelve una Promesa "pendiente" dentro de un [[PromiseResult]] con el valor que necesito, cuando llamo a getEndData() . También intenté llamar directamente a getEnd() eliminando el then() , devolviendo solo los datos, pero nada. Si res.data en console.log , devolverá el valor correcto que necesito.
Esto debería funcionar:
const Element = () => { async function getEndData() { const data = await getEnd(); return data; } } const getEnd = async () => { const response = await axios.get('http://localhost:8080/end'); return response; }No estoy seguro de que lo estés haciendo de la manera correcta. Puedes probar esto:
const Element = () => { return async function getEndData() { const data = await getEnd(); return data; } } const getEnd = () => { return new Promise((resolve, reject) => { axios.get('http://localhost:8080/end') .then(res => { resolve(res.data) }) .catch(err => { reject(err); }) }) }Además, ¿cuál es el uso de la función del elemento si no devuelve nada?
su getEndData() al devolver una promesa. agregue espera o luego, donde sea que reciba la respuesta getEndData() .
// const Element = () => { async function getEndData() { const data = (await getEnd()); return data; } // } const getEnd = async () => { return await axios.get('http://localhost:8080/end').then(res => res); } async function callEndData(){ let x = await getEndData() console.log(x) } callEndData()ya que está devolviendo la promesa y no está usando await o luego está mostrando la promesa pendiente
¿Por qué necesitas Element() ?
En caso de que necesite llamar a la función ELement y también quiera la parte de datos de la respuesta, puede intentarlo así.
const Element = async() => { async function getEndData() { return await getEnd(); } let fromEndData = await getEndData() return fromEndData } const getEnd = async () => { return axios.get('http://localhost:8080/end').then(res => { return res.data }); } async function callEndData(){ let x = await Element() console.log(x) } callEndData()en console.log(x) obtengo el valor que se pasa.