How to connect multiple conditional promises?

In my code, I have conditional tasks that all return a promise. I need tasks to be performed sequentially.

My current implementation looks something like this:

var chain = []; if (/* some condition for task A */) { chain.push(function(doContinue){ taskA().then(doContinue); }); } if (/* some condition for task B */) { chain.push(function(doContinue){ taskB().then(doContinue); }); } if (/* some condition for task C */) { chain.push(function(doContinue){ taskC().then(doContinue); }); } var processChain = function () { if (chain.length) { chain.shift()(processChain); } else { console.log("all tasks done"); } }; processChain(); 

This works great, but initially I was looking for a way to create a chain using only Promises and whole functions with .then , but I could not get a working solution.

If there is a cleaner way using only Promises and then call chains, then I would like to see an example.

+5
source share
2 answers

One possible approach:

 var promiseChain = Promise.resolve(); if (shouldAddA) promiseChain = promiseChain.then(taskA); if (shouldAddB) promiseChain = promiseChain.then(taskB); if (shouldAddC) promiseChain = promiseChain.then(taskC); return promiseChain; 

Other:

 return Promise.resolve() .then(shouldAddA && taskA) .then(shouldAddB && taskB) .then(shouldAddC && taskC); 
+9
source

You can use the new async / await syntax

 async function foo () { let a = await taskA() if (a > 5) return a // some condition, value let b = await taskB() if (b === 0) return [a,b] // some condition, value let c = await taskC() if (c < 0) return "c is negative" // some condition, value return "otherwise this" } foo().then(result => console.log(result)) 

Which is nice in this regard - besides the code is very flat and readable (imo) - the values a , b and c are available in the same area. This means that your conditions and return values โ€‹โ€‹may depend on any combination of the promised values โ€‹โ€‹of your tasks.

+1
source

Source: https://habr.com/ru/post/1260348/


All Articles