[英]How can I return the fetch API results form a function?
我想从函数返回fetch API结果。 但我得到未定义,该函数不会返回我获取的数据:
function func() { fetch('https://randomuser.me/api/?results=10') .then(response => response.json()) .then(json => (json.results)) } let users = func() console.log(users);
Fetch
是异步的并返回一个promise。 无法获取fetch返回的数据并同步访问它。 并且它无法返回users
因为该功能需要同步返回,但users
的数据将不可用。 该函数在Fetch具有来自url的响应之前返回。 没关系,这就是一切都完成了,一切都还行。
处理此问题最灵活的方法是从函数中返回promise。 然后你可以在promise的结果上使用then()
并做你需要做的任何事情:
function func(url) {
return fetch(url) // return this promise
.then(response => response.json())
.then(json => (json.results))
}
func('https://randomuser.me/api/?results=10')
.then(users => console.log(users)) // call `then()` on the returned promise to access users
.catch(err => /* handle errors */)
获取的示例可以如下:
loadJSON('https://randomuser.me/api/?results=10');
async function loadJSON(fname) {
var response = await fetch(fname)
var j = await response.json()
document.getElementById('jsondemo1').value = j.name
document.getElementById('jsondemo2').value = j.year
}
没有异步并且等待:
fetch(url).then(response => response.json())
.then(result => console.log('success:', result))
.catch(error => console.log('error:', error));
您似乎没有在函数中返回值。 如果未返回值,则您的函数将评估为undefined。
返回你的fetch调用的结果(即:json.results),并告诉我们发生了什么。
由于此调用是异步的,因此在您记录此users
undefined
users
,因为服务器尚未收到响应,您需要执行以下操作。 您可以添加then
到你的func
呼叫,则这将在已接收到响应登录的用户。
function func(url) { return fetch(url) // return this promise .then(response => response.json()) .then(json => (json.results)) } func('https://randomuser.me/api/?results=10') .then(users => console.log(users))
您需要将获取包装在Promise中并使用json数据解析它。 示例:
function func(url) {
return new Promise((resolve, reject) => {
fetch(url) // return this promise
.then(response => response.json())
.then(json => resolve((json.results)))
});
}
func('https://randomuser.me/api/?results=10')
.then(users => console.log(users))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.