En mi código, tengo una función asíncrona que devuelve una promesa. Sé que esta pregunta se ha hecho antes, sin embargo, ninguna de las soluciones funcionó.
const fetch = require('node-fetch'); async function getData() { const response = await fetch(url); return (await response.json()); } getData().then( // wait until data fetched is finished console.log(getData()) )Gracias de antemano
Creo que te estás confundiendo un poco con la sintaxis de la devolución de llamada .then() .
const fetch = require('node-fetch'); async function getData() { const response = await fetch(url); return (await response.json()); } getData().then(data => { // Notice the change here console.log(data) // Now within this block, "data" is a completely normal variable // use it as you wish })Elimine la await inútil y simplemente pase una referencia a console.log como la devolución de llamada de Promise :
const fetch = require('node-fetch'); async function getData() { const response = await fetch(url); return response.json(); } getData().then(console.log); Si no tiene más flujo de control en getData , es posible que no necesite async / await en absoluto:
const fetch = require('node-fetch'); function getData() { return fetch(url).then(x => x.json()); } getData().then(console.log);