Javascript 通过使用$.queue()按顺序(顺序)为同步和异步任务提供服务

Javascript 通过使用$.queue()按顺序(顺序)为同步和异步任务提供服务,javascript,jquery,Javascript,Jquery,我有些任务是同步的,有些是异步的。它们是混合的,但我想按顺序执行它们 图我有以下同步任务:初始化、启动、完成、终止 和下面的任务异步:task1、task2 我希望他们按以下顺序执行: 初始化、启动、任务1、任务2、完成、终止 那么,如何使用$.queue()创建它呢?下面是我的实现,但它不起作用 以下是任务代码: initialize、initiate、finalize和termiate是“愚蠢”的函数,因为它们只将消息打印到控制台日志和div项 function initialize(nex

我有些任务是同步的,有些是异步的。它们是混合的,但我想按顺序执行它们

图我有以下同步任务:初始化、启动、完成、终止 和下面的任务异步:task1、task2

我希望他们按以下顺序执行: 初始化、启动、任务1、任务2、完成、终止

那么,如何使用$.queue()创建它呢?下面是我的实现,但它不起作用

以下是任务代码:

initialize、initiate、finalize和termiate是“愚蠢”的函数,因为它们只将消息打印到控制台日志和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();
 }
但它们似乎没有按顺序执行,因为在控制台中是按以下顺序打印的:

  • 用于初始化的消息
  • 用于启动的消息
  • Task1的消息
  • Task2的消息
  • 要完成的消息
  • 用于终止的消息
  • 显示task1进度消息
  • 显示task2进度消息
  • 显示task2进度消息
  • 等等。。。混合task1和task2进度消息
  • 因为task1和task2是异步的。。。。那么如何解决这个问题呢?我想要一个非阻塞解决方案

    输出应为:

  • 用于初始化的消息
  • 用于启动的消息
  • 执行任务1 显示task1的进度消息 结束执行任务1
  • Task2的消息 显示task2的进度消息 结束执行任务2
  • 要完成的消息
  • 用于终止的消息
  • 如何将所有任务(初始化、启动、任务1、任务2、最终确定和终止)按此顺序执行?任何一段代码都将受到高度赞赏


    我使用的是jQuery 10.1.2

    应该根本不需要使用
    $.queue
    ——我相信您应该能够使用
    完成所有操作。然后()
    ,例如

    initialise().then(initiate).then(task1)...
    

    只需确保初始函数返回承诺。

    我尝试过许多类似的解决方案,但都不起作用,因为问题是Task1和Task2是异步任务。。。如何确保initialise返回承诺?我想返回$.Deferred().promise()?(我是jQuery的新手。对不起)。@user1624552是的,你可以
    返回$.Deferred().promise()
    .p.s。您的
    task1
    task2
    函数当前不会等待异步
    core
    函数完成。您还需要让
    核心
    返回一个承诺-其中延迟调用链的结果就可以了。@user1624552后者,除非您不需要在链的末尾调用
    。promise()
    ,因为
    。fail()
    已经返回了一个承诺。您确实需要返回一个承诺,但不需要创建一个新的承诺。只需在
    getTask()的前面添加
    return
      $({}).queue(initialize)
           .queue(initiate)
           .queue(Task1)
           .queue(Task2)
           .queue(finalize)
           .queue(terminate);
    
    initialise().then(initiate).then(task1)...