Pri*_* A 5 javascript jquery object promise deferred
我希望函数 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();
});
}
Run Code Online (Sandbox Code Playgroud)
请你告诉我如何让这 3 个函数调用顺序发生。
好的,您真正想要的东西已经变得更加清晰了(根据您最近解决澄清问题的评论),尽管仍然至少有两个选项可供选择。
对于这样的操作,您可能希望利用许多 Promise 功能:
.then(),并且只有当所有链接的 Promise 都已解析时,主 Promise 才会解析(类似于内置的,$.when()无需显式调用$.when())。A()都返回 Promise B(),那么这些函数的调用者可以使用 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);
Run Code Online (Sandbox Code Playgroud)
选项 2:如果您希望 5 对请求并行A()运行,只等待最后一部分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);
Run Code Online (Sandbox Code Playgroud)
它们使用这样的概念:如果您从.then()处理函数返回一个 Promise,那么它将把多个异步操作链接在一起,并且只有当所有链接的操作都得到解析时,主 Promise 才会被解析。这对于排序多个 ajax 操作非常强大,您甚至可以像您一样对循环中的操作执行此操作。