Created
February 20, 2017 18:27
-
-
Save smashingpat/083515a4ca938e16ef96b12935f50b29 to your computer and use it in GitHub Desktop.
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
import Promise from 'bluebird' | |
Promise.config({ | |
warnings: false, | |
cancellation: true, | |
}) | |
const convertJson = string => { | |
try { | |
return JSON.parse(string); | |
} catch (e) { | |
return string; | |
} | |
} | |
let lastRequest = null | |
const request = url => { | |
if (lastRequest) { | |
lastRequest.cancel() | |
} | |
const promise = new Promise((resolve, reject, onCancel) => { | |
const xhr = new XMLHttpRequest() | |
xhr.onload = () => { | |
setTimeout(function() { | |
resolve({ | |
status: xhr.status, | |
data: convertJson(xhr.responseText) | |
}) | |
}, 1000); | |
} | |
xhr.onerror = () => reject('rejected') | |
xhr.open('GET', url, true) | |
xhr.send(null) | |
onCancel(() => { | |
console.log('cancelled'); | |
xhr.abort() | |
}); | |
}) | |
lastRequest = promise | |
return promise | |
} | |
const button = document.createElement('button') | |
button.innerHTML = 'Button' | |
document.body.appendChild(button) | |
button.addEventListener('click', () => { | |
const data = request('https://jsonplaceholder.typicode.com/posts') | |
.then(console.log) | |
.catch(console.error) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment