Async function that will be added
It's a race, we're only take the first result. In case, every racer was failed we return last error
Utilities.First could be use for the same task to get the result as soon as possible.
import { Utilities } from './src/index';
(async () => {
let result = await Utilities.First(
async () => {
return heavyTask('First');
},
async () => {
return heavyTask('Second');
},
async () => {
return heavyTask('Third');
},
);
console.log('The fastest is:', result);
})();
Result:
The fastest is: Second
As you see, we have one winner here. If there are an Error
, It's fine too that meant all tasks were failed.
Async function that will be added
Try an async function several times till it's successful
Utilities.TillSuccess could be used to guarantee your request or data reach target.
import { Utilities } from './src/index';
(async () => {
let tried = 0;
// Retries heavy task each 2 second, max retries are 5 times
let result = await Utilities.TillSuccess(
async () => {
tried += 1;
console.log(`Trying ${tried} time(s)`);
return heavyTask('Yes');
},
2000,
5,
);
console.log('Was it successful?', result);
})();
Result:
Trying 1 time(s)
Trying 2 time(s)
Was it successful? Yes
If we're fail all the times, an Error
will be threw.
Could be any kind of data
Function need to be retried
Sleep for a wait
Duration in milliseconds
Generated using TypeDoc
Start everything at the same time, It will return and array of IFillResult
.Fill() Guide
We will use this code to simulate an heavy task:
/** * We simulate a heavy task * @template T * @param {T} i * @return {*} {Promise<T>} */ async function heavyTask<T>(i: T): Promise<T> { const r = 1 + Math.round(Math.random() * 9); // Sleep for a random duration await Utilities.WaitSleep(r * 500); if (r % 2 === 0) { return i; } // Throw error if r is odd throw new Error('Unexpected result'); }
Utilities.Fill will be used to perform many tasks at the same time but you can't sure about its result.
import { Utilities } from './src/index'; (async () => { let result = await Utilities.Fill( async () => { return heavyTask('First'); }, async () => { return heavyTask('Second'); }, async () => { return heavyTask('Third'); }, ); console.log(result); })();
Result:
Results of all given functions will be appeared after all promises are fulfilled.