axa-group / bauta.js

Bauta.js is an add-on for your Node.js applications such as Express.js or Fastify.
Other
42 stars 3 forks source link

bautajs-core: add decorator like parallel but that resolves Promise.race #71

Open Xavier-Redondo opened 1 year ago

Xavier-Redondo commented 1 year ago

race decorator for Promise.race

It should be nice to have a decorator race that resolves against promise.race instead of promise.all. this would allow to implement easily services that allow timeout by themselves (instead of waiting for a request to a 3rd party system to timeout).

for example (assume below code is in a resolver):


function firstPipeline() {
  return step(async (_, ctx) => {
    return new Promise(resolve =>
      setTimeout(() => {
        resolve('First pipeline returns this');
      }, 1000)
    );
  });
}

function secondPipeline() {
  return step(async (_, ctx) => {
    return new Promise(resolve =>
      setTimeout(() => {
        resolve('Second pipeline returns this');
      }, 2000)
    );
  });
}

// This resolver returns 'First pipeline returns this'
module.exports = resolver(operations => {
  operations.v1.op1.setup(race(
       firstPipeline(),
       secondPipeline()
  ));
});

Info about Promise.race

Note that promise.race settles on the first promise resolved (be that a value from a resolved promise or an exception from a rejected exception).

Promise.race Promise.race and async/await examples