愿所有的美好和期待都能如约而至

如何从函数返回Fetch API结果?

发布时间:  来源:互联网  作者:匿名  标签:api error How can I return the fetch API results from a function? exception fetc  热度:37.5℃

本文介绍了如何从函数返回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结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,

勇敢去编程!

勇敢的热爱编程,未来的你一定会大放异彩,未来的生活一定会因编程更好!

TOP