Skip to content

Instantly share code, notes, and snippets.

@smashingpat
Created February 20, 2017 18:27
Show Gist options
  • Save smashingpat/083515a4ca938e16ef96b12935f50b29 to your computer and use it in GitHub Desktop.
Save smashingpat/083515a4ca938e16ef96b12935f50b29 to your computer and use it in GitHub Desktop.
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