简体   繁体   中英

Async function returns promise after .then

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM