簡體   English   中英

將響應從獲取返回到調用它的函數

[英]Returning the response from fetch to the function which called it

我有這樣的代碼:

function getData(query){
    fetch('some-url').then((res)=>res.json())
    .then((res)=>{
      return 'string'+res.data
    })

上面的功能是

var data = getData('text');

我希望getData函數返回修改后的字符串以將其存儲在變量數據中。 我該如何實現?

function getData(query){
    return  fetch('some-url').then((res)=>res.json())
    .then((res)=>{
      return 'string'+res.data
    })

並稱它為

    getData('text').then(function(res){
       //your code should be here 
       var data=res;
    });

您可以使用async/await獲得所需的結果

function getData(query){
    return fetch('some-url').then((res)=>res.json())
    .then((res)=>{
      return 'string'+res.data
    })

然后:

var data = await getData('text'); //You will get your modified string in the data.

fetch是一個承諾,在fetch返回數據后,您只能在.then方法中更改數據。

fetch('some-url')
    .then((res) => res.json()) 
    .then((res) => 'string'+res.data)
    .then((res) => /* some code */) // in this string you can achieve data.

暫無
暫無

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

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