Created
August 31, 2018 02:59
-
-
Save songlairui/dc3d37f340ed7cd514d3f21a918f4428 to your computer and use it in GitHub Desktop.
将setTimeout的轮询包裹成Promise
This file contains 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 cache = { | |
resolve: null | |
} | |
let timerId | |
function finish(b) { | |
console.warn('---------finish-------') | |
if (cache.resolve) { | |
console.warn('---------cache.resolve-------', b) | |
cache.resolve(b) | |
} | |
delete cache.resolve | |
delete cache.reject | |
} | |
async function startPoll() { | |
const a = Math.random() | |
console.warn('execute once', a) | |
if (a > 0.93) { | |
stopPoll(`stop by ${a}`) | |
} else if (a > 0.2) { | |
timerId = setTimeout(() => startPoll(), 111) | |
} else { | |
finish(a) | |
} | |
} | |
function stopPoll(err) { | |
clearTimeout(timerId) | |
cache.reject && cache.reject(err) | |
delete cache.resolve | |
delete cache.reject | |
} | |
function main() { | |
stopPoll() | |
timerId = setTimeout(() => startPoll(), 111) | |
const currentProcess = new Promise((r, j) => { | |
if (cache.resolve) { | |
cache.resolve(currentProcess) // 接续上一个promise | |
} | |
cache.resolve = function(...x) { | |
r(...x) | |
} | |
cache.reject = function(...x) { | |
j(...x) | |
} | |
}) | |
return currentProcess | |
} | |
main() | |
.then(raw => console.warn('main result:', raw)) | |
.catch(console.warn) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment