将响应从获取返回到调用它的函数

问题描述 投票:0回答:3

我有这样的代码:

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

上面的功能是

var data = getData('text');

我希望getData函数返回修改后的字符串以将其存储在变量数据中。 我该如何实现?

javascript function return
3个回答
0
投票
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;
    });

0
投票

您可以使用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.

0
投票

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.
© www.soinside.com 2019 - 2024. All rights reserved.