theservant theservant - 5 months ago 33
Javascript Question

Javascript ES6 Promise Function Options

I have an async function which can call one of multiple other async functions; I can split this up into multiple .then.catch chains, but I'm wondering if I can merge them together somehow.
What I have is:

return new Promise((resolve, reject) => {
if (payload.method === 'a')
doFunctionA(arg)
.then((x) => resolve())
.catch((error) => reject())
else if (payload.method === 'b')
doFunctionB()
.then((x) => resolve())
.catch((error) => reject())
});


That's simplified, but is there another way to write this so that the then and catch is only written once? Like:

return new Promise((resolve, reject) => {
var f = (payload.method === 'a' ? doFunctionA(arg) : doFunctionB());
f()
.then((x) => resolve())
.catch((error) => reject())
});

Answer Source

Since doFunctionA and doFunctionB already return Promises, you don't have to wrap them in another Promise:

(payload.method === 'a' ? doFunctionA : doFunctionB)(arg)
  .then((x) => resolve())
  .catch((error) => reject())