【问题标题】:Use response of the first ajax call to the last ajax call [duplicate]使用第一个ajax调用的响应到最后一个ajax调用[重复]
【发布时间】:2020-01-31 14:46:52
【问题描述】:

我对 jquery 承诺相当陌生。 我想问一下这种情况是否可行:

我有 2 个 ajax 调用,我正在使用 .then() 链接它们两个。这就是我想做的:

ajaxCall1().then(ajaxCall1).done(functionCallHere);

我可以在ajaxCall2 中使用ajaxCall1 的响应,这是我真正打算做的。 但是,我最终想要的是在functionCallHere 中同时使用ajaxCall1ajaxCall2 的响应。

我在这里搜索过类似的问题,但我从未找到过。那么.. 是否可以在functionCallHere 中访问ajaxCall1 的回复?如果是,我该怎么做? 它是否类似于 $.when(ajax1, ajax2).done(function(r1, r2)) 的工作方式 - 比如如果您在函数中放置 2 个参数,它会自动解释为 response1 和 response2?

另外,我不想在这里使用.when(),因为我不希望调用异步运行或分叉它们。尽可能地我只想把它们锁起来。当然,如果这是唯一的方法,那么我可以恢复使用它。

非常感谢! :)

【问题讨论】:

  • 你试过了吗? ajaxCall1().then((response) => {ajaxCall2(); functionCallHere(response);})
  • 当然,你可以在里面打电话给你的functionCallHere。而且你知道你可以将你的响应传递给一个函数。
  • 谢谢!是的,这是我的第一个方法。我只是想知道是否有这样一种方法可以执行以下操作:``` .then(ajx2).then(ajx3).then(ajx4).done(functionHere) ``` 和functionHere 可以使用所有 ajax 调用响应,使其与.$.when()function(rs1, rs2, rs3) 相同,这样看起来会更干净。但是,是的,您的答案有效!非常感谢!

标签: jquery ajax promise


【解决方案1】:

您可以通过嵌套来完成。

ajaxCall1()
    .then((response) => {
         ajaxCall2()
             .then((response2) => { 
                 functionCallHere(response);
         })
    })

或者您可以在所有 ajax 调用之前定义变量。

var response1;
var response2;
ajaxCall1()
    .then((response) => {
         response1 = response; 
         ajaxCall2()
             .then((response2) => { 
                 response2 = response2; 
         })
    })
   .done(functionCallHere(response1)); // or other variable you want to pass.

您可以尝试另一种解决方案 ->

async function yourFunction() {
    var response1 = await ajaxCall1();
    var response2 = await ajaxCall2();
    functionCallHere(response1); // or other variable you want to pass.
}

注意:函数前不要错过async

【讨论】:

  • Ohhh.. 我使用的解决方案类似于第二个解决方案(在所有 ajax 调用之前定义变量)。谢谢!这真的帮助了我!在使用 asyncawait 关键字之前,我将不得不阅读它们——就像我说的,我对这个概念完全陌生。感谢您的建议!
猜你喜欢
  • 2016-06-22
  • 2015-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多