[英]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
})
删除无用的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.