0

我想启动一系列任务,我需要它们按顺序执行。当点击一个按钮(#submitButton)时,整个过程被启动(startAll函数),所以我实现了这样的架构:

function startAll()
{
   var startDeferred, highPriorityTasksDeferred, lowPriorityTasksDeferred, finalizeDeferred;

   startDeferred = $.Deferred;

   **highPriorityTasksDeferred= startDeferred.then(initialize).done(initiate); <-- ERROR HERE**

   lowPriorityTasksDeferred= highPriorityTasksDeferred.then(function () {
            console.log('Processing HIGH priority tasks...');
            return highPriorityTasks;
   })
   .done(function () {
            console.log('HIGH priority taks processed.');
   });

   finalizeDeferred= lowPriorityTasksDeferred.then(function () {
            console.log('Processing LOW priority tasks...');
            return lowPriorityTasks;
   })
   .done(function () {
            console.log('LOW priority taks processed.');
   });

   finalizeDeferred.then(finalize).done(terminate);

   // Starts all
   startDeferred.resolve();
}

function initialize() {
    // Things to be initialized just before starting process
    console.log('</br>Initiating process...');

    // Stuff

    return;
}

function initiate() {
    // Once initialized, do simple things
    setButtonDisabled(true);

    console.log('Process started at ' + $.now()+ '<br/>');

    return;
}

function finalize() {
    // Things to be done just before ending process
    // Free resources, etc.
    console.log('<br/>Finishing process...');

    // Stuff

    return;
}

function terminate() {
    // Things to be done once finished is done.
    // Simple things such as those related to UI.
    setButtonDisabled(false);

    console.log('<br/>Process terminated at ' + $.now());

    return;
}

function setButtonDisabled(status) {
    $('#submitButton').prop("disabled", status);
} 

high/lowPriorityTasks 方法的结构如下:

function high/lowPriorityTasks() {

    getTasks().then(function (response) {

       // stuff

    }).then(function () {

       // stuff 

    }).fail(function (err) {

       // stuff
    });
}

控制台输出应该是:

Initiating process...
Process started at XXX

Processing HIGH priority tasks...
HIGH priority taks processed.

Processing LOW priority tasks...
LOW priority taks processed.

Finishing process...
Process terminated at XXX

重要说明

  1. 函数初始化、启动、终结和终止,它们的最后一个命令是返回;但我不确定它是否正确。
  2. 我正在使用 jQuery 1.10.2 和 asp.net MVC 4

观察到的问题

  1. 执行它时,会引发运行时错误,指出对象不接受粗体行中的属性或方法“then”:

    highPriorityTasksDeferred= startDeferred.then(initialize).done(initiate);

第一次尝试

正如 kenneth 所说,$.Deferred 之后的括号被遗漏了,因此通过添加它们 $.Deferred() 进程被执行,但出现了一些问题: 看起来,high/lowPriorityTasks 函数没有像控制台中显示的那样执行:

Initiating process...
Process started at XXX


Finishing process...

Process terminated at XXX

有任何想法吗?我也想知道是否退货;在函数中初始化、启动、完成和终止是最好的方法,或者还有另一个最好的选择。

第二次尝试

highPriorityTasks 和 lowPriorityTasks 在调用时缺少一些括号,因此现在它们可以正确执行,但问题是它们没有按顺序完成......

4

1 回答 1

1

您在 . 之后缺少括号$.Deferred。目前它返回的是延迟函数而不是延迟对象。

将其更改为以下内容,它应该可以工作:

startDeferred = $.Deferred();
于 2013-09-24T13:03:00.927 回答