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

人气:323 发布:2022-10-16 标签: javascript api fetch

问题描述

我想从函数返回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 */)

590