Created
December 5, 2018 18:00
-
-
Save DC3/12dbac91a0ddb7991fef3a96b35e289b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const resolved = Promise.resolve(); | |
class Deferred { | |
constructor() { | |
const p = new Promise((resolve, reject) => { | |
this.resolve = resolve; | |
this.reject = reject; | |
}); | |
this.then = p.then.bind(p); | |
this.catch = p.catch.bind(p); | |
} | |
} | |
function delay(time = 0) { | |
if (!time) { | |
return resolved; | |
} | |
return new Promise(r => setTimeout(r, time)); | |
} | |
function sequence(array, func) { | |
return (array || []).reduce((seq, ...args) => seq.then(() => func(...args)), resolved); | |
} | |
function promiseProxy(func, isOnce, isResolve) { | |
let result; | |
let promise; | |
let run = false; | |
function reset() { | |
run = false; | |
} | |
return (...args) => { | |
if (isOnce && result) { | |
return isResolve ? Promise.resolve(result) : Promise.reject(); | |
} | |
if (run && promise) { | |
return promise; | |
} | |
run = true; | |
promise = new Promise((res, rej) => { | |
const p = func.apply(null, args); | |
if (p && p.then && typeof p.then === 'function') { | |
p.then(r => { | |
reset(); | |
result = r; | |
res(r); | |
}).catch(e => { | |
reset(); | |
rej(e); | |
}); | |
} else { | |
reset(); | |
res(p); | |
} | |
}); | |
return promise; | |
}; | |
} | |
function onceResolve(func) { | |
return promiseProxy(func, true, true); | |
} | |
function onceReject(func) { | |
return promiseProxy(func, true); | |
} | |
function waitFinish(func) { | |
return promiseProxy(func); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment