0

I am using fetch api inside a function so in success response i want to insert the value into a global variable but it is not doing this.

example code is

function getExcludeDates(){

 var data; 

 fetch('/get-exclude-dates')
 .then(res => res.text())
 .then(text => {
    data = text.data;
    //$('#students_count_reservation').prop('disabled', true);
 });

return data;
}

return data shows undefined in console log

Hassaan
  • 319
  • 2
  • 26
  • 1
    res.text() or res.json() – Mohammed Ashfaq Sep 19 '18 at 14:23
  • 1
    ☝️ None of this will make any difference. The answer is simply: *you can't.* – deceze Sep 19 '18 at 14:24
  • What do you mean by return data? `res.text` or the `data`? I feel the `return data` should move insde the async call (second `then`) – CRayen Sep 19 '18 at 14:24
  • 1
    @CRayen you can't return out of a synchronous function from a callback. – Luke Ramsden Sep 19 '18 at 14:25
  • res.text is an array and whatever i write whether res.json or res.text no matter i just want to put the value of result in a variable which i can return as callback result – Hassaan Sep 19 '18 at 14:29
  • 1
    Again, You. Can. Not. You want to `return fetch(...).then(...)` to return *a promise* from `getExcludeDates`, and then in the caller you will need to asynchronously handle the promise. You cannot synchronously return the value immediately, because it doesn't exist immediately. – deceze Sep 19 '18 at 14:34
  • After your advice i am doing this and getting result without fetch api async function getExcludeDates(){ var data = await getdates() return data; } function getdates(){ return new Promise(resolve => { resolve(text.data); }); } but i am not getting any result when i put fetch api inside resolve obj – Hassaan Sep 19 '18 at 14:52
  • @deceze thanks for suggestion please submit your answer i will accept that .. you were right, intead of res.text() i had to use res.json() and i got the value from promise obj – Hassaan Sep 19 '18 at 18:21

0 Answers0