0

I have a code something like this:

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

The above function is

var data = getData('text');

I want the getData function to return modified string to store it in the variable data. How do I achieve this?

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
Chirag
  • 73
  • 1
  • 7
  • Not an export in promises, but what if you tried `return fetch('some-url').then((res)=>res.json()) .then((res)=>{ return 'string'+res.data })` – Nick Parsons Dec 26 '18 at 12:26
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Dmitry Dec 26 '18 at 12:27
  • @Dmitry didn't understand that – Chirag Dec 26 '18 at 12:35
  • @NickParsons Not working. Returns promise – Chirag Dec 26 '18 at 12:35

3 Answers3

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

and call it like

    getData('text').then(function(res){
       //your code should be here 
       var data=res;
    });
Ahmed Ghoniem
  • 661
  • 1
  • 8
  • 15
0

You can use async/await to achieve the desired result

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

Then:

var data = await getData('text'); //You will get your modified string in the data.
Harish Soni
  • 1,796
  • 12
  • 27
0

fetch is a Promise, and you can change data only in .then method after fetch returned your data.

fetch('some-url')
    .then((res) => res.json()) 
    .then((res) => 'string'+res.data)
    .then((res) => /* some code */) // in this string you can achieve data.
Vadim Hulevich
  • 1,803
  • 8
  • 17