Search code examples
javascriptfunctionreturn

Returning the response from fetch to the function which called it


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?


Solution

  • 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;
        });