Javascript在另一个异步函数结束时调用函数

Javascript call function when another asynchronous function ends

本文关键字:函数 结束 调用 异步 另一个 Javascript      更新时间:2023-09-26

我有一个实现一些httprequest的函数。当所有这些请求完成时,我需要刷新父窗口并关闭当前窗口。但是现在,当前窗口在完成请求之前就关闭了,并且请求没有正确完成。下面是我的代码:

<script>
        function save()
        {
            $.when( insert() ).done(function() {
                opener.location.reload();
                window.close();
            });
        }
        function insert()
        {
            $('select').each(function () {
                var idTraslado = $(this).attr("id");
                var accion = $(this).val();
                //the page realizes mysql updates. 
                xmlhttp = new XMLHttpRequest();
                xmlhttp.open("GET","trasladosEliminarMultipleGuardar.php?idTraslado="+idTraslado+"&accion="+accion+"&motivo="+motivo,true);
                xmlhttp.send();
            });
        }
    </script>

你必须使用承诺,否则when在你的代码中没有用处:

function save()
{
    $.when(insert()).done(function () {
        opener.location.reload();
        window.close();
    });
}
function insert()
{
    var promises = [];
    $('select').each(function () {
        var deferred = $.Deferred();
        var idTraslado = $(this).attr("id");
        var accion = $(this).val();
        //the page realizes mysql updates. 
        xmlhttp = new XMLHttpRequest();
        xmlhttp.onload = function (response) {
            deferred.resolve(response);
        };
        xmlhttp.open("GET", "trasladosEliminarMultipleGuardar.php?idTraslado=" + idTraslado + "&accion=" + accion + "&motivo=" + motivo, true);
        xmlhttp.send();
        promises.push(deferred.promise());
    });
    return promises;
}