我有一些任务是同步的,而另一些是异步的。它们是混合的,但我想按顺序执行所有这些。
图像我有以下任务同步:初始化,启动,完成,终止和以下任务异步:任务 1、任务 2
我希望它们按以下顺序执行:初始化、启动、任务 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);
但似乎它们没有按顺序执行,因为在控制台中按以下顺序打印:
- 用于初始化的消息
- 用于启动的消息
- 任务 1 的消息
- 任务 2 的消息
- 要完成的消息
- 终止消息
- 显示任务 1 进度消息
- 显示任务 2 进度消息
- 显示任务 2 进度消息
- 等等...混合任务 1 和任务 2 进度消息
因为任务 1 和任务 2 是异步的。那么如何解决这个问题呢?我想要一个非阻塞的解决方案。
输出应为:
- 用于初始化的消息
- 用于启动的消息
- 执行任务1显示任务 1 的进度消息结束执行任务1
- 任务 2 的消息显示任务 2 的进度消息结束执行任务2
- 要完成的消息
- 终止消息
如何按此顺序对它们进行排队(初始化、启动、任务 1、任务 2、完成和终止(?任何一段代码都将不胜感激。
我正在使用jQuery 10.1.2
根本不需要使用$.queue
- 我相信你应该能够用.then()
来完成这一切,例如
initialise().then(initiate).then(task1)...
只需确保初始函数返回 Promise。