用javascript同步两个进程
synchronizing two process in javascript
我的问题是我有两个不同的函数在运行,其中有ajax调用,这使它们异步。当两者都完成时,我必须启动第三个函数。问题是异步性质,我可以知道它们何时结束。有这样的解决方案:
- 使它们同步
- 把一个人置于另一个人的成功之中
但这两者都会导致延迟,因为这些ajax调用带来了大数据,所以最好让它们异步。
有人能给我推荐一种更清洁的方法吗。
function f1(){
//AJAX call}
function f2(){
//ajax call}
when f1 and f2 are done fire f3().
我认为您正在寻找的是jQuery.done((:https://api.jquery.com/deferred.done/
示例:
// 3 functions to call when the Deferred object is resolved
function fn1() {
$( "p" ).append( " 1 " );
}
function fn2() {
$( "p" ).append( " 2 " );
}
function fn3( n ) {
$( "p" ).append( n + " 3 " + n );
}
// Create a deferred object
var dfd = $.Deferred();
// Add handlers to be called when dfd is resolved
dfd
// .done() can take any number of functions or arrays of functions
.done( [ fn1, fn2 ], fn3, [ fn2, fn1 ] )
// We can chain done methods, too
.done(function( n ) {
$( "p" ).append( n + " we're done." );
});
// Resolve the Deferred object when the button is clicked
$( "button" ).on( "click", function() {
dfd.resolve( "and" );
});
$.when( f1(), f2() ).done(function( a1, a2 ) {
// a1 and a2 are arguments resolved for the f1() and f2() ajax requests, respectively.
});
var async1 = $.get('hello.php');
var async2 = $.get('world.php');
$.when(async1, async2).done(function(hello, world) {
// this function will be called only if async1 and async2 are resolved
console.log(hello);
console.log(world);
});
https://api.jquery.com/jQuery.when/
相关文章:
- JQuery合并了keyup和focusout两个函数
- 如何使用 node.js 比较两个 json 数组
- 为复选框javascript指定两个值
- 用每小时的差值填充数组/列表-从下拉列表中给定两个时间值
- 单击时切换两个图像
- 我可以'我似乎不知道如何修复javascript中的两个lint.有人能帮我理解吗
- 基于两个条件退出While循环
- 如何在这里将两个值最低的数字相加
- 组合两个javascript函数
- 如何使用offer/answer交换来自两个对等连接的流
- jsf中两个字符串的颜色代码差异
- 加载两个具有相同父密钥名称的json文件
- 在Qualtrics中,介绍如何动态连接两个滑块
- 访问$.ajax()函数中的两个不同数组
- 在一个node.js进程中组合两个主循环
- 从单节点进程提供两个https主机名&港口城市
- 如何确保两个或多个节点进程(child_process)中的逻辑同步
- 用javascript同步两个进程
- Electron中两个渲染器进程之间的通信
- 如何在jQuery中处理两个进程