【问题标题】:jQuery promises and dependent AJAX callsjQuery 承诺和依赖的 AJAX 调用
【发布时间】:2014-03-08 18:56:48
【问题描述】:

我想知道如何使用 jQuery 的 promises/deferred 进行依赖 AJAX 调用。现在我有这样的东西:

$.when($.ajax('https://somedomain.com/getuserinfo/results.jsonp', {
  dataType      : 'jsonp',
  jsonp         : true,
  jsonpCallback : 'userCallback'
}))
.then(function (data) {
  return $.when($.getJSON('http://www.otherdomain.com/user/' + data.userId), $.getJSON('http://www.anotherdomain/user').then(function (json1, json2) {
    return {
      json1  : json1,
      json2  : json2
    };
  });
});

它按预期对我有用,但我不知道这是否是正确的方法。您对如何改进有什么建议吗?

【问题讨论】:

  • 您应该将其移至代码审查。 codereview.stackexchange.com
  • 好吧,我的问题是这样的做法是否正确?
  • 您还没有解释您想要实现的确切原因,因此我们无法真正为您想要做的任何事情提供更好的方法。您可以使用$.ajax(...).then(...) 而不是$.when($.ajax(...)).then(...),但这就是现在要说的全部内容。

标签: javascript jquery ajax promise jquery-deferred


【解决方案1】:

好吧,您的代码似乎已经“正确”运行了,尽管还有一些地方需要改进:

$.when($.ajax(…))

这里不需要$.when$.ajax 已经返回了一个承诺。

$.when($.getJSON(…), $.getJSON(…).then(…)

您在此处的某处缺少右括号 - 可能在 .then 之前。假设:

….then(function(…){ return ….then(function(…){…}); })

由于 promises 是一元的,你可以unnest这些回调到

…
.then(function(…){ return …; })
.then(function(…){…})

为了避免末日金字塔。


jQuery 特有的:

$.when(…).then(function (json1, json2) {
  return {
    json1: json1,
    json2: json2
  };
});

$.when 之后的回调参数不是普通结果,而是每个getJSON 延迟解析的arguments objects。您可能只想要第一个索引上的 JSON:

$.when(…).then(function (json1, json2) {
  return {
    json1: json1[0],
    json2: json2[0]
  };
});

【讨论】:

  • 好的,谢谢。但这不是我问题的答案。我的问题是如何进行依赖 AJAX 调用。我的意思是我从第一个来源(在 $.when 中)获取用户详细信息,根据我从中获得的数据,我同时对两个不同的来源进行两次 AJAX 调用,并将来自第一个来源的用户详细信息作为另一个 AJAX 的参数发送来电。
  • 这就是我在第一句话中的回答:就像你做的一样!
  • 谢谢,我只是觉得它在某些方面可能不正确。
猜你喜欢
  • 2018-07-30
  • 1970-01-01
  • 2014-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多