繁体   English   中英

异步 function 返回 promise after.then

[英]Async function returns promise after .then

在我的代码中,我有一个异步 function,它返回一个 promise。我知道之前有人问过这个问题,但是没有一个解决方案有效。

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

先感谢您

我认为您对.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
})

这个答案与 Guerric 的含义相似,但希望以更适合初学者的方式呈现:)

删除无用的await ,只需将console.log的引用作为Promise回调传递:

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

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

getData().then(console.log);

如果您在getData中没有更多控制流,则可能根本不需要async / await

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

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

getData().then(console.log);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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