连续调用多个函数
call multiple functions successively
我知道这个问题已经被问了好几次了,但是我似乎无法获得使用我的代码的解决方案:等到一个带有动画的函数完成,直到运行另一个函数,jquery等待多个完整事件,等待两个异步函数结束,然后再触发第三个(jQuery延迟?
基本上,我想依次调用四个函数:
#1
function getJason() {
$.getJSON(rgUrl1,function(json1){
rgJson1 = json1; ...etc.
});
#2
function combineJason() {
//code to combine
});
#3
function divideArray() {
//code to divide stuff
});
#4
function doOtherStuff() {
//code to do some other stuff
});
我需要 #1 在调用 #2 之前完成,#2 在 #3 之前完成,#3 在 #4 之前完成。 过去的帖子让我相信我应该使用延期和承诺。 我已经通读了文档 http://api.jquery.com/category/deferred-object/并尝试了示例但没有成功:
function testing() {
var deferredObj = $.Deferred();
var test = getJson()
var function1 = function () {
test.done(function(){
deferredObj.resolve();
return deferredObj;
});
}
deferredObj.done(function(){
combineJson();
});
};
此外,大多数示例处理两个函数,而我需要调用几个函数。 我还注意到一些响应包含"setTimeout"。 我有点怀疑,也许是不必要的,使用任何带有计时器、暂停或延迟的东西。 那我就不必猜测该功能需要多长时间吗? 如果一个用户的计算机/连接速度较慢或其他原因怎么办?
jQuery的ajax函数已经返回了一个承诺。因此,如果您使用的是jquery的ajax函数,则不需要创建新的延迟对象。
若要连续调用函数:调用 .then
方法以获取需要调用的函数数。如果一个或多个函数需要执行一些异步任务,则只需返回一个 promise,延迟对象将等待调用下一个then
回调,直到返回的承诺解析。每个then
回调都将传递前then
返回的数据(或者在返回的情况下承诺解析的数据(
$.getJSON(rgUrl1,function(json1){
rgJson1 = json1; ...etc.
}).then(combineJason)
.then(divideArray)
.then(doOtherStuff);
//#2
function combineJason(someData) {
//code to combine
return $.getJSON("url to some other json endpoint");
}
//#3
function divideArray(someData) {
//code to divide stuff
//this function is sync so just return some data
return someNewData;
}
//#4
function doOtherStuff(someData) {
//code to do some other stuff
//this function is async so return a promise;
return $.getJSON("url to some other json endpoint");
}
JSFiddle Demostrating 混合异步/同步继承
连续调用它们非常容易,您不需要等待多个异步事物,而只需等待前一个异步事物。
你会做的
function getJason() {
return $.getJSON(rgUrl1);
}
function combineJason(json1) {
//code to combine
}
function divideArray() {
//code to divide stuff
}
function doOtherStuff() {
//code to do some other stuff
}
getJason().then(combineJason).then(divideArray).then(doOtherStuff);
这将非常类似于
doOtherStuff(divideArray(combineJason(getJason())));
只是如果一个结果是异步的(在这里,$.getJSON
getJason
中(,它才需要注意延迟计算(作为回调(。
- 是否可以将一个函数输入连接到另一个函数调用的文本
- 在输入字段上有两个函数调用,一个在Blur上,一个不在Angular中
- 如何在Javascript函数调用中循环变量
- Javascript:应为赋值或函数调用,但实际看到的却是表达式
- 如何远程检查JavaScript应用程序的函数调用堆栈
- javascript函数调用不起作用
- 为什么这个函数调用会破坏程序并导致未定义的变量
- 如何通过函数调用设置图像的src
- 从全局函数调用Ember控制器上的方法
- 为什么Jquery$.ajax在函数调用中触发所有statusCode,即使调用成功
- JavaScript函数调用(arg1)(arg2)
- 打印链接时,将javascript函数调用到链接中
- 在函数调用中封装数据除了隐藏数据之外还有什么优点
- 无法从JavaScript中的函数调用对象属性
- 对中的函数调用进行排序是回调的唯一方法
- 函数调用方法有什么用
- Javascript:JSHint:应为赋值或函数调用,但实际看到的却是表达式
- HTML5(Bootstrap)通过函数调用运行动画
- 函数调用不起作用
- 函数中的Javascript函数调用