Home > Net >  Async function returns promise after .then
Async function returns promise after .then

Time:01-18

In my code, I have an async function that returns a promise.I am aware that this question has been asked before, however none of the solutions worked.

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())
)

Thank you in advance

CodePudding user response:

I think you're just getting a little bit confused with the syntax of the .then() callback.

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
})

This answer similar in meaning to Guerric's, but hopefully presented in a more beginner-friendly way :)

CodePudding user response:

Remove the useless await and just pass a reference to console.log as the Promise callback:

const fetch = require('node-fetch');

async function getData() {
  const response = await fetch(url);
  return response.json();
}

getData().then(console.log);

If you don't have more control flow in getData, you might not need async/await at all:

const fetch = require('node-fetch');

function getData() {
  return fetch(url).then(x => x.json());
}

getData().then(console.log);
  •  Tags:  
  • Related