中断可能なPromise
用途
重い処理を途中で中断する
まだテストしていないですtakker.icon
2021-02-06 14:54:34 だめだった
無理そう
code:script.js
export function abortableCallback(callback){
let timeoutId = null;
let resolve = undefined;
const promise = new Promise(res => {
resolve = res;
timeoutId = setTimeout(() => {
timeoutId = null;
(async () => {
await callback();
res();
})();
}, 0)
});
return {
promise,
cancel: () => {
if (!timeoutId) return;
clearTimeout(timeoutId);
timeoutId = null;
resolve();
},
};
}
test code
code:js
(async ()=>{
const sleep = async msec => new Promise(res => setTimeout(() => res(), msec));
const {abortableCallback} = await import('/api/code/programming-notes/中断可能なPromise/script.js');
const {promise, cancel} = abortableCallback(async () => {
console.log('func start!!')
await sleep(1000)
console.log('func finish!!')
});
await sleep(400);
cancel();
})()
Qiita.icon