Skip to content

Instantly share code, notes, and snippets.

@songlairui
Created August 31, 2018 02:59
Show Gist options
  • Save songlairui/dc3d37f340ed7cd514d3f21a918f4428 to your computer and use it in GitHub Desktop.
Save songlairui/dc3d37f340ed7cd514d3f21a918f4428 to your computer and use it in GitHub Desktop.
将setTimeout的轮询包裹成Promise
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