Search code examples
javascripttypescriptpromisees6-promise

How to ensure execution order in TypeScript


I'm trying to implement some functionalities when I end Up having an issue about execution order in typescript:

code:

new Promise((resolve) => {
          setTimeout(()=>{
            console.log("function11111");
            resolve();
          }
          ,3000);      
          
        })
        .then(_=>{
          setTimeout(()=>{
            console.log("function22222");
          }
          ,2000);   
        })
        .then(_=>{
          setTimeout(()=>{
            console.log("function3333333");
          }
          ,1000);   
        }) 

The OutPut:

function11111
function33333
function22222

My Questions are:

1)for function1111, if we replace this console.log('fucntion1111') by a function that takes some seconds, in this case, my code will fire resolve() before the function finish its execution, So how to ensure the wait for my function

2)In my code I'm doing then then, Why the execution doesn't respect my order ? I was thinking that promise is created for this purpose.


Solution

  • The issue is that all the then handlers are invoked at the same time once the initial resolve() is called. And since each has a different timeout, hence the order of output as function33333 and then functon2222.

    To maintain an order , you can do promise chaining which will wait for previous promise to get resolve , before invoking the next then() block.

    I have chained the promises. Do let me know if you need more clarification.

    new Promise((resolve) => {
          setTimeout(()=>{
            console.log("function11111");
            resolve();
          }
          ,3000);
    
        })
        .then(_=> new Promise(resolve => {
          setTimeout(()=>{
            console.log("function22222");
            resolve();
          }
          ,2000);
          })
        )
        .then(_=> new Promise(resolve => {
          setTimeout(()=>{
            console.log("function3333333");
            resolve();
          }
          ,1000);
          })
        );