-1

If I had two independent functions that are usually called separately like below:

   function one() {
        axios.post('XXXX', {
           foo: foo,
        })
        .then((response) => {
            //do something;
        });
    }

   function two() {
       axios.post('YYYY', {
          foo: foo,
       })
       .then((response) => {
           //do something;
       });
   }

but somewhere in my code, I had another function that called both of these but the execution was important in where I need two() to run and finish executing before one() does, I realize this below is unreliable.

function all() {
     two();
     one();   
}

I want to ensure the times where I call these functions together elsewhere, I get them in the correct order and that the first finishes executing before the second is called. Can I have rewrite the function two() so it will return a Promise that just resolves() with no argument inside of it so that it will trigger one() like follows:

function two() {
    return new Promise((resolve, reject) => {
      axios.post('YYYY', {
         foo: foo,
      })
      .then((response) => {
          //do something;
      })
      .then((response) => {
          resolve();
      });
    }      
}
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
raulInsto
  • 85
  • 11

2 Answers2

0

It's not an anti-pattern, and is in fact a great use case for async/await:

async function all() {
     await two();
     await one();   
}

will ensure that two completes before one begins.

dave
  • 62,300
  • 5
  • 72
  • 93
-2

Can I rewrite the function two() so it will return a Promise

Yes, you can, and yes, you should! Returning a promise to signal when the work is done is a best practice and should totally be done by every asynchronous function - not just two but also one and all. Fulfilling the promises with undefined is fine when there's no useful result, although it would be more meaningful to return the response data and just ignore it at the call site when you don't need it.

Can I call resolve()?

No, you should avoid the Promise constructor antipattern! Use promise chaining, where the promise result is the return value of the callback:

function one() {
    return axios.post('XXXX', {
//  ^^^^^^
       foo: foo,
    }).then(response => {
        // do something
        return undefined; // or something else
    });
}

// same for `two`

function all() {
    return two().then(one);
}

or with async/await:

async function one() {
    const response = await axios.post('YYYY', {
       foo: foo,
    })
    // do something
    return undefined; // or something else
}

// same for `two`

async function all() {
    await two();
    await one();   
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375