-1

Let's say I have the following function getData

getData = (param) => {
    // jquery
    $.ajax(...).done(..)
}

How do I turn getData into a blocking function so that refreshPage only gets called after the ajax within getData is done?

data = getData(..)
refreshPage()

Please note: I don't want to pass refreshPage into the ajax callback within getData

OK... here is what I tried and seems working:

getData = (param) => {
    // jquery
    return $.ajax(...).done(..)
}
getData.then(refreshPage())
James Lin
  • 25,028
  • 36
  • 133
  • 233
  • 1
    `getData` cannot be a blocking function, unless you make AJAX synchronous (which is a very bad idea). `await getData(...)` can be made quasi-blocking, if the containing function is `async` (by making `getData` return a promise). Is that what you mean? – Amadan Jun 18 '19 at 04:05
  • Just wrap it in a `Promise` that resolves when you get the data? – jhpratt Jun 18 '19 at 04:06
  • 1
    @jhpratt There's no point in wrapping it in promise, `$.ajax` already returns a perfectly nice one (assuming `$` is jQuery). – Amadan Jun 18 '19 at 04:07
  • And given no mention of jQuery, I haven't assumed that. Conversion from a `Promise` to `async`/`await` certainly has a million dupes by itself. – jhpratt Jun 18 '19 at 04:08
  • sorry forgot to mention it's jquery – James Lin Jun 18 '19 at 04:10
  • I mean, `$`, followed by `ajax` followed by `done` is highly likely to be jQuery or jQuery-like – Avin Kavish Jun 18 '19 at 04:11
  • Assuming $.ajax() is jQuery is a pretty straightforward assumption @jhpratt. Simply using `async / await` should do the trick. – Gaurav Punjabi Jun 18 '19 at 04:11

4 Answers4

3
function getData = (param) => {
    // jquery
    return $.ajax(...);
}

async test() {
    var x = await getData()
    console.log(x)
}
Ziv Ben-Or
  • 1,149
  • 6
  • 15
  • This is pretty close to what I have tried,which I used `getData().then(..)`, I cannot verify if using `await getData()` because webpack throws error on me. – James Lin Jun 18 '19 at 04:22
1
getData = (param) => $.ajax(...).done(..)

getData().done(() => refreshPage())
// or
getData().done(refreshPage)
Avin Kavish
  • 8,317
  • 1
  • 21
  • 36
1

You may try the following:

function getData (param)
{
   ...........       
   return new Promise((resolve, reject) =>{
        jQuery.ajax({...});
   });
}
...........

getData(param).then(()=>refreshPage());
The KNVB
  • 3,588
  • 3
  • 29
  • 54
0

you should return a promise from your get data method

getData = (param) => {
    return new Promise(function(resolve, reject) {
   }
}

then when things are done in ajax called resolve(data) there

Syed Afzal
  • 150
  • 1
  • 8