如何从函数中返回 fetch API 结果?

How can I return the fetch API results form a function?(如何从函数中返回 fetch API 结果?)
本文介绍了如何从函数中返回 fetch API 结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个函数返回 fetch 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 是异步的并返回一个promise.无法获取 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 的结果上使用 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 */)

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)