我有一些同步和其他异步的任务。他们是混合但我想按顺序执行所有这些。
图像我有以下任务同步:初始化,启动,完成,终止 以下任务异步:task1,task2
我希望它们按以下顺序执行: 初始化,启动,任务1,任务2,完成,终止
那么如何使用$ .queue()?在我的实现下面,但它不起作用。
在任务代码下面:
初始化,启动,终止和终止是“愚蠢”的功能,因为它们只将消息打印到控制台日志和div项目。
function initialize(next) {
// Here initialization stuff is done just before starting the entire process: things that are required later during the process
console.log('Initiating process...');
postStatus('</br>Initiating process...');
next();
}
function initiate(next) {
// Here enable/disable buttons are done
setButtonDisabled(true);
console.log('Process started.');
postStatus('Process started <br/>');
next();
}
function finalize(next) {
// Here things required to be done just before terminating the entire process should be done.
// Free resources, etc.
console.log('Finishing process...');
postStatus('<br/>Finishing process...');
next();
}
function terminate(next) {
// Here things that need to be done when the entire process finished.
// Simple things such as those related to UI.
setButtonDisabled(false);
console.log('Process terminated.');
postStatus('<br/>Process terminated.');
next();
}
其余的:
function core(urlGetData, urlDoTask) {
getTasks(urlGetData).then(function (response) {
console.log("Response from getTasks: " + response);
postResponse(response, "Received GetData results" + JSON.stringify(response));
if ("fail" === response.status) {
return fail(response);
}
console.log(response);
return doTasks(response.data, urlDoTask);
}).then(function () {
postStatus("Received DoTask results");
var results = arguments;
console.log(results);
for (var i = 0; i < results.length; i++) {
postResponse(results[i], 'done ' + JSON.stringify(results[i]));
}
}).fail(function (err) {
postStatus("Error: " + JSON.stringify(err));
});
}
function Task1(next) {
if ($('#Task1').is(':checked')) {
core("/MyController/GetDataTask1/", "/MyController/DoTask1/");
}
next();
}
function Task2(next) {
if ($('#Task2').is(':checked')) {
core("/MyController/GetDataTask2/", "/MyController/DoTask2/");
}
next();
}
按钮点击我执行:
$({}).queue(initialize)
.queue(initiate)
.queue(Task1)
.queue(Task2)
.queue(finalize)
.queue(terminate);
但似乎它们没有按顺序执行,因为在控制台中它按此顺序打印:
因为task1和task2是异步的....所以如何解决这个问题呢?我想要一个非阻塞的解决方案。
输出应为:
如何按顺序执行它们(初始化,启动,task1,task2,finalize和terminate)的排队顺序?任何一段代码都将受到高度赞赏....
我正在使用jQuery 10.1.2
答案 0 :(得分:0)
根本不需要使用$.queue
- 我相信您应该能够使用.then()
完成所有操作,例如
initialise().then(initiate).then(task1)...
确保您的初始函数返回Promise。