Javascript在另一个异步函数结束时调用函数
Javascript call function when another asynchronous function ends
我有一个实现一些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;
}
相关文章:
- 函数1结束后,JavaScript调用函数2
- JavaScript - 回调 - 等待多个函数结束
- 使用 JavaScript 显示 XML 数据,在函数结束时出现问题
- 等待函数结束(在 async.series 中)无法按预期工作
- 函数结束时如何运行代码
- Javascript等待函数结束,包括来自node.js的异步MYSQL查询
- 等待异步 Javascript 函数结束检索结果(延迟?)
- Jquery 执行函数 第三方函数结束后
- 如何在调用它的函数结束时执行回调
- 在所有cordova.exec函数结束后执行成功回调
- 在上一个js函数结束后运行js函数
- 直到函数结束,才会显示模式引导
- 函数结束后显示MessageBox
- Javascript对象在创建它的函数结束后被设置为未定义
- Node.js回调,等待函数结束
- 在函数结束时用javascript播放音乐
- Javascript在另一个异步函数结束时调用函数
- 事件.PreventDefault直到函数结束才会起作用
- 在JavaScript中,等待一个函数结束后再开始另一个函数
- 如何正确插入回调函数,使一个函数结束,然后执行另一个函数