简体   繁体   中英

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); 

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

An example of fetch can be as follow:

loadJSON('https://randomuser.me/api/?results=10');
async function loadJSON(fname) {
    var response = await fetch(fname)
    var j =  await response.json()
    document.getElementById('jsondemo1').value = j.name
    document.getElementById('jsondemo2').value = j.year
}

Without async and await:

fetch(url).then(response => response.json())
  .then(result => console.log('success:', result))
  .catch(error => console.log('error:', error));

It does not seem like you are returning a value in your function. Your function will evaluate to undefined if a value is not returned.

Return the result of your fetch call (ie: json.results), and tell us what happens.

As this call is asynchronous users is undefined when you are logging this as a response has not been received by the server you need to do the following. You can add then to your func call which will then log users when a response has been received.

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

You need to wrap the fetch inside a Promise and resolve it with the json data. Example :

function func(url) {
    return new Promise((resolve, reject) => { 
        fetch(url)  // return this promise
        .then(response => response.json())
        .then(json => resolve((json.results)))
    });
}

func('https://randomuser.me/api/?results=10')
    .then(users => console.log(users))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM