我希望函数 A 完成执行,然后函数 B 才开始执行。当我调用函数 A 然后调用函数 B 时,似乎两者同时执行。在函数 B 完成后,我想调用第三个函数 update_dropdown()。
我的代码是这样的:
function A {
for (var i = 0; i < 5; i++) {
var promise = $.get(url+i);
$.when(promise).then(function () {
$.post(url);
});
}
}
function B {
var x = $.get(url);
var promise = $.post(url+x);
$.when(promise0).then(function () {
update_dropdown();
});
}
请告诉我如何让这 3 个函数调用按顺序发生。
最佳答案
好吧,尽管仍然至少有两个选择,但您真正想要的东西变得更清楚了(根据您最近对澄清问题的评论)。
对于这样的操作,您可能希望利用一些 promise 功能:
- jQuery 的 Ajax 调用已经返回一个 promise ,因此您可以直接使用它们
- 要序列化操作,您可以将多个 promise 操作链接在一起
- 要使异步操作正确序列化,您可以从
.then()
处理程序返回一个 promise,只有当所有链接的 promise 都已解析时,master promise 才会解析(一种内置的$.when()
而无需显式调用$.when()
)。 - 您可以根据需要将任意数量的操作链接在一起,当它们全部完成时,master promise 会告诉您。
- 如果您从
A()
和B()
返回 promise,那么这些函数的调用者可以监视它们何时完成 promise 方法,然后让您链A().then(B)
对这两个进行排序。 - 当您使用链接对操作进行排序时,先前的方法解析数据将传递给链中的下一个
.then()
处理函数作为.then()< 的第一个参数
处理函数,因此如果您需要下一个操作的先前数据,就可以使用它。
因此,有了所有这些功能,只需围绕代码放置正确的脚手架即可实现您想要的精确排序。这里有两个不同的选项:
选项 1:如果您想序列化 A()
中的所有内容,以便所有 10 个请求都以串行方式发生(仅当前一个请求是完成),那么它可能看起来像这样:
// serialize all requests
function A() {
var p = $.get(url).then(function(data) {return $.post(url)});
for (var i = 1; i < 5; i++) {
// chain four more pairs of requests onto the original promise
p = p.then(function() {return $.get(url)})
.then(function(data) {return $.post(url)});
}
// return the promise so callers can monitor when A() is done
return p;
}
function B() {
// sequence these three operations one after the other
return ($.get(url)
.then(function(data) {return $.post(url + x)})
.then(update_dropdown)
);
}
// run them both, one after the other
A().then(B);
选项 2:如果您希望 A()
中的 5 对请求并行运行,只有 A()
等待 5 对请求完成,然后它可能看起来像这样:
// parallelize pairs of requests
function A() {
var promises = [];
for (var i = 0; i < 5; i++) {
// execute 5 pairs of requests where each pair is serialized in itself
promises.push($.get(url).then(function(data) {return $.post(url)}));
}
// return a promise that resolves only when all the other promises are done
return $.when.apply($, promises);
}
function B() {
// sequence these three operations one after the other
return ($.get(url)
.then(function(data) {return $.post(url + x)})
.then(update_dropdown)
);
}
// run them both, one after the other
A().then(B);
这些使用的概念是,如果您从 .then()
处理程序函数返回一个 promise,那么它会将多个异步操作链接在一起,只有当所有链接操作都完成时,主 promise 才会被解析。解决。这对于对多个 ajax 操作进行排序非常强大,您甚至可以像现在这样对循环中的操作执行此操作。
关于javascript - javascript中的顺序函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23451163/