Skip to content

Instantly share code, notes, and snippets.

@DadgadCafe
Last active March 23, 2017 04:49
Show Gist options
  • Save DadgadCafe/24b14d6cc8c1da75b0829f48a32720ad to your computer and use it in GitHub Desktop.
Save DadgadCafe/24b14d6cc8c1da75b0829f48a32720ad to your computer and use it in GitHub Desktop.
cancel the ajax call after settled time.
const fakeAjax = (time, cb) => {
setTimeout(() => {cb('data...')}, time)
}
const noopPromise = new Promise(() => {})
// cancel promise when timeout reached, using Promise.race
const timer = (fn, time) =>
Promise
.race([
new Promise(fn),
new Promise((resolve, reject) => {
setTimeout(() => {reject(Error('time out'))}, time)
})
])
.catch(
// stop the chain, coz it is pending.
() => noopPromise
)
timer(
function (resolve, reject) {
// data fetched after 2s
fakeAjax(500, resolve)
},
// cancel after 2s
1000
)
// not called.
.then(data => {console.log(data)})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment