0

The following contains promises, synchronous statements inside if else. Is there a way execute it in sequence i.e. fragment 1,2,3,4 and keep it in one piece using then chain rather than making each fragment a function and calling them for every if else ? For instance Fragment 2,3,4 should be executed after fragment 1 whether category is MAIN or not.

// Start Fragment 1
    if (category == "AUXILIARY") fncAuxiliary() //synchronous function
    if (category == "MAIN") fncMain() // returns promise
// End Fragment 1

// Start Fragment 2
    if (category != "AUXILIARY")
    if (type == "REGRADE") {
       fncSelectProduct().then( () => {  // returns promise
            //other synchronous code
            fncProduct1();    //synchronous function
        });
    }
    else{
        fncSelectProduct().then( () => {     // returns promise
             //other synchronous code
             fncProduct2(); //synchronous function
        });
    }
// End Fragment 2

// Start Fragment 3
    if (type == "REGRADE") {
     //synchronous code
    }
    else if (category !="AUXILIARY") {
     //synchronous code
    }
    else if (category =="AUXILIARY") {
     //synchronous code
    }
// End Fragment 3

// Start Fragment 4
    if (category !="AUXILIARY")
    if(type == "MECHANICAL"){
       fncSelectEquipment().then( () => {    // returns promise
            //other synchronous code
            return fncEq1()    // returns promise
        }).then( () => {
             //synchronous code
        });
    }
    else if(type == "OPERATIONAL"){
        fncSelectOpsEquipment().then( () => {    // returns promise
           //other synchronous code
           return fncEq2()  // returns promise
         }).then( () => {
           //synchronous code
         });
    }
    else if(type == "PROCESS"){
         //synchronous code
    }
    else if(type == "ROUTINE"){
         //synchronous code
    }
// End Fragment 4
catalin
  • 5
  • 3
  • Easiest solution would be `async`/`await`. But no, you'd need to put each fragment code in a function - and there's nothing wrong with that. You don't need to name it though, see e.g. https://stackoverflow.com/q/26599798/1048572. – Bergi Mar 21 '21 at 15:47

1 Answers1

1

You can make use of async await to deal with this easily. Chaining things in .then will make your code look confusing eventually. Refer the snippet below for an async await version of your code

const fragment = async (category) => {
  if (category == "AUXILIARY") console.log("Hello"); //synchronous code
  if (category == "MAIN") await fetch("/").then(console.log, console.error);
  if (category)
    await fetch("/").then(() => console.log("This runs after previous fetch"));
};
const main = async () => {
  await fragment("MAIN");
  console.log("Code after fragment");
};
main();

You can read more about async/await here - https://javascript.info/async-await

Saurav
  • 197
  • 8