我想从一个函数中返回fetch API的结果,但是我得到了undefined,并且这个函数没有返回我获取的数据:
function func() {
fetch('https://randomuser.me/api/?results=10')
.then(response => response.json())
.then(json => (json.results))
}
let users = func()
console.log(users);
我想从一个函数中返回fetch API的结果,但是我得到了undefined,并且这个函数没有返回我获取的数据:
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 */)
users
是undefined
,因为服务器尚未收到响应,您需要执行以下操作。您可以在func
调用中添加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))
Users
可以移动到函数块中,然后进行赋值,最后函数可以返回该变量。这样就少了一个全局变量 :-) - NnanyielugoloadJSON('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),并告诉我们发生了什么。
then
是一个 Promise 语法,第二个 then
调用会在 Promise 被解决或拒绝后执行,在这种情况下,错误将被转发到 catch 块。 - Nnanyielugothen()
中设置值之前返回未定义的值。 - Markfunction 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))
then
已经返回了一个 Promise
,不需要再包装成另一个 Promise
。只需要添加 return
即可。 - JojOatXGME