小羊也疯狂 2017-05-19 08:48 采纳率: 100%
浏览 1802
已采纳

关于es6入门,看到promise的时候发现两个小问题,不知道是怎么回事

问题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);
});


书上的例子我稍微改一改,为什么就不能异步执行了

  • 写回答

2条回答 默认 最新

  • Go 旅城通票 2017-05-19 09:48
    关注

    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,所以计时器没什么反应

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器