1

I have a function that should do a few things simultaneously. For that I call to other functions that return a Promise, like so:

async function do_things(params){
    return new Promise((resolve,reject)=>{
        const first_promise=perform_first(params);
        const second_promise=perform_second(params);

        let [first_result,second_result]=await Promise.all([first_promise,second_promise]);
        ...
        resolve();
    });
}

That should pretty much do the trick. Now I want to add .then(res) and .catch(err) blocks to log both 'res' and 'err'.

Should I do that on do_first(params).then((res)=>{...}).catch((err)=>{...}); or on first_result.then((res)=>{...}).catch((err)=>{...});? (obviously the second can be done likewise)

Fcmam5
  • 4,888
  • 1
  • 16
  • 33
Michiel
  • 123
  • 11
  • 1
    [What is the explicit promise construction antipattern and how do I avoid it?](https://stackoverflow.com/q/23803743) | [Is it an anti-pattern to use async/await inside of a new Promise() constructor?](https://stackoverflow.com/q/43036229) – VLAZ Feb 24 '23 at 11:05
  • elaborating on that, the function just being `return Promise.all([first_promise,second_promise])` will probably do what you need – ACarter Feb 24 '23 at 11:14

1 Answers1

1

As I understood from your post:

What you are trying to do looks exactly like the use case of Promise.all() or Promise.allSettled() which thy both return promises, so no need to wrap it with new Promise..

If you want to perform something that requires both promises to be resolved you can do:

async function do_things(params) {
  const first_promise = perform_first(params);
  const second_promise = perform_second(params);

  return Promise.all([first_promise, second_promise]);
}

// somewhere else in your code
try {
    await do_things(params)

    // do things if both promises are resolved
} catch (error) {
    // well, you know 
}

Or if need to run both tasks and then resolve the promise from do_things anyways you may use Promise.allSettled which unlike Promise.all it doesn't reject once one of your promises is rejected

async function do_things(params) {
  const first_promise = perform_first(params);
  const second_promise = perform_second(params);

  return Promise.allSettled([first_promise, second_promise]);
}

// somewhere else in your code
const things = await do_things(params)

things.forEach(something => {
    if (something.status === "fulfilled") {
        console.log(something.value);
    } else { // status is "rejected"
        console.error(something.reason)
    }
});
Fcmam5
  • 4,888
  • 1
  • 16
  • 33