-1

I did some research on stackoverflow, but I didn't find an answer to my problem, and I still cannot comment, so I can't ask.

I have an asynchronous method from which I need to get a return value to a method which calls it:

somefunc(data) {
  var x = filterSwear(data);
  // do sth...
  // ...
}

function filterSwear(msg) {
  var xx;
  $.get('/swearWords.csv', function(data) {
    var swearWords = data.split(',');
    for(var i = 0; i < swearWords.length; i++) {
      var subs = "***";
      var x = "".concat("\b" + swearWords[i] + "\b"); // !
      var reg = new RegExp(x, "gi");
      xx = msg.replace(reg, subs);
    }
    //console.log(xx);
  });
  //console.log(xx);
  return xx;
}

The problem is to get the data back to the first function. Or should I maybe continue with the original function in there, where I have the data?

P.S. I found a partial answer to my question here

Community
  • 1
  • 1
Mark
  • 253
  • 1
  • 5
  • 22
  • jQuery ajax functions return promise objects - you can simply return the result of the $.get call to the calling function, and access the ajax response through the callbacks – kinakuta Oct 29 '14 at 18:45
  • I am a bit inexperienced in this matter, can you please explain a bit more about which object attributes I need to access so I can get the data? – Mark Oct 29 '14 at 18:47
  • Which data do you want to get? – Qullbrune Oct 29 '14 at 18:50
  • from xx in the $.get() method – Mark Oct 29 '14 at 19:08

1 Answers1

1

You need to re-write your code using callbacks so that you have a way to continue execution once asynchronous operations complete:

somefunc(data) {

  var onFilterSwearSearchComplete = function(x){    //will be called once async stuff completes in filterSwear
    //x here is the 'xx' value from filterSwear
  };
  filterSwear(data, onFilterSwearSearchComplete);
}

function filterSwear(msg, callback) {
  $.get('/swearWords.csv', function(data) {
    var subs = "***";
    var x = "".concat("\b" + swearWords[i] + "\b"); // !
    var reg = new RegExp(x, "gi");
    xx = msg.replace(reg, subs);
    callback(xx);
  });
}
p e p
  • 6,593
  • 2
  • 23
  • 32