async-singleton
Promiseをひとつだけ実行するやつ
code:script.js
export function asyncSingleton(callback) {
if (typeof callback !== 'function') throw new Error('argument is not function.')
let queue = [];
let isRunning = false;
return (...parameters) => new Promise(async resolve => {
console.log({isRunning});
if (isRunning) {
queue.forEach(pair => pair.resolve({state: 'canceled'}));
return;
}
isRunning = true;
resolve({result: await callback(...parameters), state: 'fullfilled'});
if (queue.length > 0) queue.forEach(async pair =>
pair.resolve({result: await callback(...pair.parameters), state: 'fullfilled'}));
queue = [];
isRunning = false;
});
}