</div>
</div>
<div class="grid--cell mb0 mt4">
<a href="/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call" dir="ltr">How do I return the response from an asynchronous call?</a>
<span class="question-originals-answer-count">
(38 answers)
</span>
</div>
<div class="grid--cell mb0 mt8">Closed <span title="2014-10-29 18:55:32Z" class="relativetime">5 years ago</span>.</div>
</div>
</aside>
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
</div>
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);
});
}