如何从函数返回Fetch API结果?
本文介绍了如何从函数返回Fetch API结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从函数返回Fetch API结果。但我没有定义,该函数没有返回获取的数据:
数据-lang=”js”数据-隐藏=”假”数据-控制台=”真”数据-巴贝尔=”假”>
function func() {
fetch('https://randomuser.me/api/?results=10')
.then(response => response.json())
.then(json => (json.results))
}
let users = func()
console.log(users);
推荐答案
Fetch
是异步的,返回承诺。无法同步获取和访问FETCH返回的数据。无法返回users
,因为函数需要同步返回,但users
的数据不可用。该函数在FETCH收到来自URL的响应之前返回。没关系,每件事都是这样做的,而且一切都还在继续。
处理此问题的最灵活方法是只从函数返回承诺。然后,您可以对承诺的结果使用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 */)
这篇关于如何从函数返回Fetch API结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,