簡體   English   中英

如何從函數返回fetch API結果?

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

我想從函數返回fetch API結果。 但我得到未定義,該函數不會返回我獲取的數據:

 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的響應之前返回。 沒關系,這就是一切都完成了,一切都還行。

處理此問題最靈活的方法是從函數中返回promise。 然后你可以在promise的結果上使用then()並做你需要做的任何事情:

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

獲取的示例可以如下:

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
}

沒有異步並且等待:

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

您似乎沒有在函數中返回值。 如果未返回值,則您的函數將評估為undefined。

返回你的fetch調用的結果(即:json.results),並告訴我們發生了什么。

由於此調用是異步的,因此在您記錄此users undefined users ,因為服務器尚未收到響應,您需要執行以下操作。 您可以添加then到你的func呼叫,則這將在已接收到響應登錄的用戶。

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

您需要將獲取包裝在Promise中並使用json數據解析它。 示例:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM