0

I need to run multiple async operations, until one of them returns a certain result - in other words, the "Chain of Responsibility" pattern.

When I tried to implement it, some was the first thing that came up. However I'm having troubles with the asynchronous calls, as the loop gets "stuck" after the first iteration:

asyncCalls.some(async (call) => {
    const result = await call();
    if (result === expectedResult) {
        printResult(result);
    }
    return result === expectedResult;
});

Is there any way to iterate an array of async functions, with the possibility to break upon receiving a certain response?

GalAbra
  • 5,048
  • 4
  • 23
  • 42
  • "*Is there any way to iterate an array of async functions, with the possibility to break upon receiving a certain response?*" yes, use a regular loop. – VLAZ Aug 11 '21 at 19:27
  • And how do you wait in a regular loop until the async call is finished? – GalAbra Aug 11 '21 at 19:28
  • You use `await`. It's the only way to wait for an async function to finish (outside using the Promise API). – VLAZ Aug 11 '21 at 19:29

2 Answers2

1

Try this

for (const call of asyncCalls) {
  const result = await call();
  if (result === expectedResult) {
    printResult(result);
    break;
  }
}
Christian
  • 7,433
  • 4
  • 36
  • 61
0

Here's an idea

const runFunc = (asyncCalls,expectedResult) => {

 return new Promise((res,rej) => {
    Promise.all(asyncCalls.map(async (call) => {
       const result = await call();
       if (result === expectedResult) {
           res(result);
      
       }
       return result === expectedResult;     
    
    }))
    // if it hasn't been fullfilled, reject
    .then(() => rej()).catch((err) => rej(err));
 });

}
Adam Jenkins
  • 51,445
  • 11
  • 72
  • 100
  • What is the point of `Promise.all`? The only real reason to use it is to [avoid the `async` constructor](https://stackoverflow.com/questions/43036229/is-it-an-anti-pattern-to-use-async-await-inside-of-a-new-promise-constructor) but it does the same thing anyway. It's just a doing simple loop in a promise executor function but with more steps. Which wouldn't even be needed if `runFunc` was async. – VLAZ Aug 11 '21 at 19:42