繁体   English   中英

Javascript ajax 同步请求不起作用

[英]Javascript ajax synchronous request is not working

我正在为我的网站发出连续的 AJAX 请求。 有 2 个 POST 请求。 第二个请求应该在第一个请求完成后处理。 我的代码如下:

$.ajax({
    type: 'POST',
    url: '/backend/edge/enableNewAgent/',
    async: false,
    success: function () {
        console.log("First Process Done");
    }
});
$.ajax({
    type: 'POST',
    url: '/backend/edge/deleteOldAgent/',
    async: false,
    success: function () {
        console.log("Second Process Done");
    }
});

第二个进程在第一个进程之后完成,但是控制台日志是在第二个进程完成后执行的,而不是在第一个进程完成之后。 我希望在第一个进程完成后立即执行console.log ,然后继续执行第二个进程。 有人可以帮忙吗?

使用async: false意味着您永远不会屈服于事件循环,并且console.log行会排队(所有其他显示更新也是如此)。

我的方法是这样的:

function enableNewAgent() {
    return $.post('/backend/edge/enableNewAgent/',
        () => console.log('enableNewAgent Done')
    );
}

function deleteOldAgent() {
    return $.post('/backend/edge/deleteOldAgent/',
        () => console.log('deleteOldAgent Done')
    );
}

enableNewAgent().then(deleteOldAgent);

如果您需要进一步的操作,请将它们添加到.then链中:

enableNewAgent().then(deleteOldAgent).then(nextOperation);

如果您想编写同步的“外观”代码并避免同步 XMLHttpRequest - 您可以使用 async/await

async function doAjax() {
    await $.ajax({
        type: 'POST',
        url: '/backend/edge/enableNewAgent/',
        success: function() {
            console.log("First Process Done");
        }
    });
    await $.ajax({
        type: 'POST',
        url: '/backend/edge/deleteOldAgent/',
        success: function() {
            console.log("Second Process Done");
        }
    });
}

实际上,最好这样做

async function doAjax() {
    await $.ajax({
        type: 'POST',
        url: '/backend/edge/enableNewAgent/'
    });
    console.log("First Process Done");
    await $.ajax({
        type: 'POST',
        url: '/backend/edge/deleteOldAgent/'
    });
    console.log("Second Process Done");
}

请注意,它必须在一个函数内完成(不必像这样是一个单独的函数,只需将其放在那里以强制执行这个想法...... await仅在async函数内)

你可以试试

$.ajax({
  type: 'POST',
  url: '/backend/edge/enableNewAgent/',
  success: function() {
    console.log("First Process Done");
  }
}).then(function(){
      $.ajax({
      type: 'POST',
      url: '/backend/edge/deleteOldAgent/',
      success: function() {
        console.log("Second Process Done");
      }
    });

暂无
暂无

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

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