如何返回$ .get()的值?

时间:2014-10-29 18:43:14

标签: javascript jquery ajax asynchronous

我对stackoverflow做了一些研究,但是我没有找到问题的答案,我仍然无法评论,所以我不能问。

我有一个异步方法,我需要从中获取一个调用它的方法的返回值:

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

问题是将数据恢复到第一个功能。 或者我应该继续使用原始功能,我有数据吗?

P.S。我找到了对我的问题here

的部分答案

1 个答案:

答案 0 :(得分:1)

您需要使用回调重新编写代码,以便在异步操作完成后有办法继续执行:

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