Skip to main content

promise and priority

ながい遅延やまちがった優先度があると、error が発生することが度々あります。 今回は promisepriority で、同期的かつ順番に実行できるようにします。 codesandbox の demo があるので、よろしければあそんでみてください。


promiseAtom

promise.then から function を追加することで、同期実行できるようになります。 demoでは、block が interact した順に fade out していきます。

promiseAtom test - CodeSandbox


then から function を追加し、最新の Promise をcurrent に保存します。

function makePromise(executor = (resolve) => resolve()) {
let current = new Promise(executor);
return {
finally: (fun) => (current = current.finally(fun)),
catch: (fun) => (current = current.catch(fun)),
then: (fun) => (current = current.then(fun))
};
}

priorityAtom

priority number により、同期的かつ順次実行ができるようになります。 demo では、高さ y は priority number なので高いブロックから消えます。

priorityAtom test - CodeSandbox


function の追加ごとに sort し、実行時は先頭の function を実行します。 binary heep で function を sort すると、より performance tuning できそうです。

function makePriority(executor = (resolve) => resolve()) {
const promise = makePromise(executor);
const current = [];
return {
finally: (fun) => promise.finally(fun),
catch: (fun) => promise.catch(fun),
then: (fun, priority = -1) => {
current.push([priority, fun]);
current.sort(([i], [j]) => i - j);
promise.then(async () => await current.shift()[1]());
return promise;
}
};
}