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

Moh*_*mad 7 javascript api fetch

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);
Run Code Online (Sandbox Code Playgroud)

Mar*_*yer 13

Fetch是异步的并返回一个承诺。没有办法把fetch返回的数据同步访问。并且它不能返回,users因为函数需要同步返回但数据users不可用。该函数在 Fetch 收到来自 url 的响应之前返回。没关系,这就是一切完成的方式,并且仍然有效。

处理这个最灵活的方法是从函数中返回承诺。然后你可以使用then()Promise 的结果并在那里做任何你需要做的事情:

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 */)
Run Code Online (Sandbox Code Playgroud)


Ull*_*nka 1

fetch 的示例如下:

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
}
Run Code Online (Sandbox Code Playgroud)

没有异步和等待:

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