阻止方法返回'undefined'

时间:2015-07-23 17:11:00

标签: javascript jquery jquery-callback

我不熟悉回调并尝试让它发挥作用。我不希望我的getCustomerIdDescription在我的帖子返回数据之前向我的popover返回任何内容,但是我在底部的'callback(supplierId)'行中出现错误,该行显示'回调不是函数'如何编写我的回调,以便在我获得我的帖子数据之前不会从getCustomerIdDescription返回任何内容?

这是我的代码

scope.showCustomerIdList = function(value) {
  $('#{0}'.format(value)).popover({
    html: true,
    container: 'body',
    content: function() {
      return scope.getCustomerIdDescription(value);
    },
    title: function() {
      return 'Customer ID - Description';
    }
  }).popover('show');
};

scope.getCustomerIdDescription = function(supplierId, callback) {
  var model = {};
  model.clientId = scope.contextClientId;
  model.supplierId = supplierId;
  $.post(scope.enumControllers.GetCustomerIdsForSupplier, model, function(response) {
    if (response.error == false) {
      var ids = JSON.parse(response.ids);
      var list = '';
      _.each(ids, function(result) {
        list += '<li>' + result.CustomerId + ' - ' + result.CustomerDescription + '</li>';
      });
      return '<ul>' + list + '</ul>';
    } else {
      return "Cound't Fetch Customer Ids";
    }
  }).fail(function() {
    return "Cound't Fetch Customer Ids";
  });
  callback(supplierId);
};

2 个答案:

答案 0 :(得分:3)

你打电话:

scope.getCustomerIdDescription(value);

但你定义:

scope.getCustomerIdDescription = function(supplierId, callback) {

由于您未向其传递值,callbackundefined

然后你:

callback(supplierId);

...没有进行测试以查看callback是否为函数。

或者:

  • 删除该行
  • 将其包裹在确保函数通过
  • 的测试中
  • 当您致电getCustomerIdDescription
  • 时,始终将函数作为第二个参数传递

顺便说一句,如果在发送Ajax请求后立即调用回调函数,则没有太多意义。将它放在您在请求中设置的回调函数中通常更有意义。

答案 1 :(得分:1)

为了使您的代码能够运行,请尝试以下方法,并了解 Asynchronicity 的方法和概念,请访问Asynchronicity

scope.showCustomerIdList = function(value) {
 scope.getCustomerIdDescription(value, function(content){
  $('#{0}'.format(value)).popover({
    html: true,
    container: 'body',
    content: function() {
            return content;
    },
    title: function() {
      return 'Customer ID - Description';
    }
    }).popover('show');
 });
}

scope.getCustomerIdDescription = function(supplierId, callback) {
  var model = {};
  model.clientId = scope.contextClientId;
  model.supplierId = supplierId;
  $.post(scope.enumControllers.GetCustomerIdsForSupplier, model, function(response) {
    if (response.error == false) {
      var ids = JSON.parse(response.ids);
      var list = '';
      _.each(ids, function(result) {
      list += '<li>' + result.CustomerId + ' - ' + result.CustomerDescription + '</li>';
      });
      callback('<ul>' + list + '</ul>');

    } else {
      return "Cound't Fetch Customer Ids";
    }
  }).fail(function() {
    return "Cound't Fetch Customer Ids";
  });     
};