如何从函数返回获取API结果? [英] How can I return the fetch API results form a function?

查看:102
本文介绍了如何从函数返回获取API结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从函数返回获取API结果.但是我不确定,并且该函数不会返回我获取的数据:

I want to return fetch API result from a function. but I get undefined and that function doesn't return me fetched data :

function func() {
    fetch('https://randomuser.me/api/?results=10')
    .then(response => response.json())
    .then(json => (json.results))
}

let users = func()

console.log(users);

推荐答案

Fetch是异步的,并返回承诺.无法获取取回返回的数据并对其进行同步访问.而且它不能返回users,因为该函数需要同步返回,但users的数据将不可用.该函数在Fetch收到URL响应之前返回.没关系,这就是所有步骤的完成方式,并且仍然可以正常使用.

Fetch is asynchronous and returns a promise. There is no way to take the data returned by fetch and access it synchronously. And it can't return users because the function needs to return synchronously but the data for users won't be available. The function returns before Fetch has a response from the url. That's okay, that's how everything is done and it all still works.

处理此问题的最灵活方法是仅从函数中返回promise.然后,您可以对promise的结果使用then(),并在那里做任何需要做的事情:

The most flexible way to handle this is to just return the promise from the function. Then you can use then() on the result of the promise and do anything you need to do there:

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 */)

这篇关于如何从函数返回获取API结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆