问题1:promise实现ajax请求的时候 resolve里面的参数 this.response 是什么,
ajax里面好像没有这个属性,是不是应该是respinseText
var getJSON = function(url) {
var promise = new Promise(function(resolve, reject){
var client = new XMLHttpRequest();
client.open("GET", url);
client.onreadystatechange = handler;
client.responseType = "json";
client.setRequestHeader("Accept", "application/json");
client.send();
function handler() {
if (this.readyState !== 4) {
return;
}
if (this.status === 200) {
resolve(this.response); //这里this.response
} else {
reject(new Error(this.statusText));
}
};
});
问题2.
settimeout 第3个参数实际上是第一个参数的函数的参数,而 resolve又是能传递参数的
function timeout(ms) {
return new Promise((resolve, reject) => {
setTimeout(resolve, ms, 'done'); //改成 setTimeout(resolve('done'), ms);
});
}
timeout(5000).then((value) => {
console.log(value);
});
书上的例子我稍微改一改,为什么就不能异步执行了
this是当前的xhr实例对象,response属性用的比较少用,2进制数据,一般用responseText和responseXML属性的多
具体可以看这个:http://www.ruanyifeng.com/blog/2012/09/xmlhttprequest_level_2.html
你可以把responseType设为blob,表示服务器传回的是二进制对象。
var xhr = new XMLHttpRequest();
xhr.open('GET', '/path/to/image.png');
xhr.responseType = 'blob';
接收数据的时候,用浏览器自带的Blob对象即可。
var blob = new Blob([xhr.response], {type: 'image/png'});
setTimeout(resolve('done'), ms);
你这个是马上执行revole,返回done给promise了,直接打印出结果。。然后将revole的返回值,注意是返回值作为setTimeout延时执行的函数,resolve返回undefined,所以计时器没什么反应
使用js写东西,不知道对象是什么的时候就对应打印出来看看啊, 对于handle里面的this你可以看下,这个handle赋值给了 client对象的onreadystatechange,也就是说这个this就是client(猜测)所以this.response,就是对应这个request的消息返回。
对于下面那个 setTimeout( fun, time ) 如果改成 resolve('done') 意味着 settimeout的执行函数绑定的是 resolve的返回值,意思是在没有启用timeout的时候 你就把promise状态设置为已解决。