I'm learning promise about ecma6,I want to get the json data by promise.then(),but it doesn't work by the callback of resolve.I test in chrome under version 44.
the result is
<button type="button" id="get">get</button>
<script type="text/javascript">
var ele = document.getElementById('get');
ele.addEventListener('click', testPromise, false);
var getData = function (url) {
var promise1 = new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.setRequestHeader('Accept', 'application/json');
xhr.send();
xhr.onreadystatechange = handler;
xhr.responseType = 'json';
function handler () {
console.log('status: ' + this.status);
if (this.status === 200) {
console.log(this.response);
resolve(this.response);
} else {
reject(new Error(this.statusText));
}
}
});
return promise1;
}
function testPromise() {
getData('http://1.frontendlife.sinaapp.com/test/promise.json').then(function (json) {
console.log(json);
}, function (error) {
console.log(error);
});
}
</script>