简体   繁体   中英

Multiple dependency promise chain

I'm trying to implement the following use case:

  1. I've a sequence of sync tasks
  2. Each sync task need to trigger an async task
  3. Async tasks cannot run concurrently, so each one wait both for its trigger (2) and the completion of its predecessor.

在此处输入图片说明

My first idea was to convert every task (sync & async) into a promise then create two promise chains. But I'm struggling finding a way to implement the async tasks chain with double dependency.

How can I achieve this ?

Actually if your "sync tasks" are really synchronous, you can simply run them synchronously before starting your chain of asynchronous tasks and the condition that every "async task" runs after its respective "sync task" is trivially met, because all async tasks run after all sync tasks.

If your "sync tasks" are actually asynchronous themselves, or somehow run really parallel to each other (I don't know about the threading/concurrency model of ExtendScript), you should make each of the tasks (whether "sync" or "async") return a promise.

You can then build your chain network (acyclic graph) of dependencies using Promise.all :

var syncResult1 = syncTask1();
var asyncResult1 = syncResult1.then(asyncTask1);
var syncResult2 = syncResult1.then(syncTask2);
var asyncResult2 = Promise.all([asyncResult1, syncResult2]).then(asyncTask2);
var syncResult3 = syncResult2.then(syncTask3);
var asyncResult3 = Promise.all([asyncResult2, syncResult3]).then(asyncTask3);

(If your "sync tasks" don't need to return promises, just make it syncResult… = syncTask…(syncResult…) )

You only need one promise chain:

syncTask1();
var promise1 = asyncTask1(); // Triggers first async task
syncTask2();
var promise2 = promise1.then( asyncTask2 );
syncTask3();
var promise3 = promise2.then( asyncTask3 );
...

Of course you would want to name your tasks and promises meaningfully. This will behave identically to this though, since JavaScript is single threaded and all the sync tasks will complete before the promise of asyncTask1 can resolve:

syncTask1();
var promise1 = asyncTask1(); // Triggers first async task
syncTask2();
syncTask3();
...
var promise2 = promise1.then( asyncTask2 );
var promise3 = promise2.then( asyncTask3 );
...

From the diagram it looks like Async2 and 3 depend on more than just fullfillment of the relative Sync function,

Using your naming conventions this is how I'd chain the promises:

               Synctask1
               |       |
             Sync2    Async1
             |     \     |
           Sync3    Async2(resolved with promiseAll[Async1, Sync2]
                \     |
                 \    |
                 Async3(resolved with promiseAll[Async2, Sync3]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM