Last active
March 23, 2017 04:49
-
-
Save DadgadCafe/24b14d6cc8c1da75b0829f48a32720ad to your computer and use it in GitHub Desktop.
cancel the ajax call after settled time.
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 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