Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I return the fetch API results form a function?

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);
like image 437
Mohammad Avatar asked Jul 19 '18 07:07

Mohammad


1 Answers

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.

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 */)
like image 126
Mark Avatar answered Nov 08 '22 10:11

Mark