Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
145 views
in Technique[技术] by (71.8m points)

javascript - How to know which condition failed in a multiple condition typescript

I want to know which one of these conditions failed (if one of them fails)

What would be the ideal solution?

Code I'm using right now:

const multiCondition =
  (await firstCondition()) &&
  (await secondCondition()) &&
  (await thirdCondition());

if (multiCondition) {
...
} else {
  // failed, (which one)???
}

Edit:

Every condition is dependent from the previous one.

question from:https://stackoverflow.com/questions/66051649/how-to-know-which-condition-failed-in-a-multiple-condition-typescript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Right now all your promises execute serially. Is that intentional? If you want them all to execute in parallel, the easiest way to get the status of each is Promise.allSettled.

If you want them to run in serial, you could loop over all the conditions, and if it fails, short circuit and return the failure status for the rest of them. If they all succeed, it will just return an empty object.

const conditions = [firstCondition, secondCondition, thirdCondition];

const result = await conditions.reduce(async (status, condition, index) => {
   // If we've already failed, don't run the current condition,
   // just return the failure status
   if(status.failed) {
     return status;
   }

   // Otherwise, run the condition..
   const test = await condition();

   // If it succeeded, return the accumulator, otherwise set the status
   // to failed, so the next runs will short circuit
   return test ? status : { failed: true, failedAt: index }
}, {});

if(result.failed) {
   console.log('condition failed: ', conditions[result.failedAt]);
}

And you can shorten the above code to something like

const conditions = [firstCondition, secondCondition, thirdCondition];

const result = await conditions.reduce(async (status, condition, index) =>
  status.failed ?
  status :
  await condition() ?
  status :
  { failed: index },
  {}
);

if('failed' in result) {
   console.log('condition failed: ', conditions[result.failed]);
}

and then clean it up into a utility function:

const promiseAnd = (...conditions) => await conditions.reduce(async (status, condition, index) =>
  status.failed ?
  status :
  await condition() ?
  status :
  { failed: index },
  {}
);

const { failed } = await promiseAnd(firstCondition, secondCondition, thirdCondition);
if(failed) {
  console.log(`Promise ${failed} failed`);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...