繁体   English   中英

与2个AJAX调用一起使用时

[英]Using when with 2 AJAX calls

我有两个功能.. addItemremoveItem POST到给定的URL。 这些AJAX调用工作正常。 但是,它们需要同步。 我正在尝试使用.when使它们同步。 我的代码基本上如下所示:

$.when(additem()).done(removeItem());

但这似乎无法正常工作,并且请求同时被触发。

我还尝试将功能之一放在请求的complete中,如下所示:

$.ajax({
  type: "POST",
  url: '/cart/update.js',
  data: {updates: updates},
  dataType: 'json', 
  complete: removeItem()
});

但这似乎也不起作用。在启动下一个AJAX请求之前,正确的方法是什么?

谢谢

引用功能和调用功能之间是有区别的。

  • 要引用功能,请仅使用其名称。
  • 要调用一个函数,请在函数名后加上括号。

设置回调(异步或非异步)时,您要引用该函数,而不是调用它。 在第二个函数调用之后加上括号,该调用将立即发生。

尝试这个:

$.when(additem()).done(removeItem);

要么:

$.ajax({
  type: "POST",
  url: '/cart/update.js',
  data: {updates: updates},
  dataType: 'json', 
  complete: removeItem
});

如果需要将参数传递给回调,则必须使用括号,但为避免调用,应将函数包装在另一个函数声明中,如下所示:

$.when(additem()).done(function(){
  removeItem(<arguments here>);
});

要么:

$.ajax({
  type: "POST",
  url: '/cart/update.js',
  data: {updates: updates},
  dataType: 'json', 
  complete: function(){
    removeItem(<arguments here>);
  }
});

问题在于您如何称呼他们。 您要立即调用这两个函数,而不是将它们作为$.whendone参数传递。

由于$.ajax返回一个Promise(或类似Promise的对象),因此您可以完全省略$.when .。

 function addItem() { // $.ajax returns a Promise-like object return new Promise(function(resolve, reject) { console.log('Adding an item...'); setTimeout(function() { console.log('Item has been added'); resolve(); }, 2000); }); } function removeItem() { return new Promise(function(resolve, reject) { console.log('Removing an item...'); setTimeout(function() { console.log('Item has been removed'); resolve(); }, 2000); }); } // Promises implement a `then` function which runs when the promise resolves addItem() .then(removeItem); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

您可以使用jquery-ajaxQueue

或修改您的代码:

$.ajax({
  type: "POST",
  url: '/cart/update.js',
  data: {updates: updates},
  dataType: 'json', 
  complete: removeItem
});

请记住,有一件事是,如果在函数后看到括号,则表示“执行”,因此,如果为callback complete设置removeItem() ,则不会按预期那样调用它。 将其设置为complete时将调用它。

其他答案已经解决了您正在调用函数并传递结果而不是传递要调用的函数的事实。 该答案旨在强调ECMAScript 2017语言规范(ES8)中引入的新的异步等待功能。

从下面的代码片段中可以看到,每一行在执行之前都会等待上一行完成; 而如果没有async和await,则每行都将执行而无需等待异步调用完成。

 const asyncFunc = text => new Promise((resolve, reject) => { setTimeout(() => resolve(text), 1000) }) async function main() { const hello = await asyncFunc("hello") console.log(hello) const world = await asyncFunc("world") console.log(world) } main() 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM