weixin_33738578 2019-10-13 11:43 采纳率: 0%
浏览 67

承诺的AJAX

How to use promises (ES6) and .then method in order to this code will work?

getGif: function (searchingText, callback) {
        var url = GIPHY_API_URL + '/v1/gifs/random?api_key=' + GIPHY_PUB_KEY + '&tag=' + searchingText;
        var xhr = new XMLHttpRequest();
        xhr.open('GET', url);
        xhr.onload = function () {
            if (xhr.status === 200) {
                var data = JSON.parse(xhr.responseText).data;
                var gif = {
                    url: data.fixed_width_downsampled_url,
                    sourceUrl: data.url
                };
                callback(gif);
            }
        };
        xhr.send();
    },
  • 写回答

1条回答 默认 最新

  • csdnceshi62 2019-10-14 09:49
    关注

    Using Promise-Based XHR your code looks like:

    getGif = function (searchingText) {
      return new Promise((resolve, reject)=>{
    
            var url = GIPHY_API_URL + '/v1/gifs/random?api_key=' + GIPHY_PUB_KEY + '&tag=' + searchingText;
            var xhr = new XMLHttpRequest();
            // Setup our listener to process compeleted requests
            xhr.onreadystatechange = function () {
    
                // Only run if the request is complete
                if (xhr.readyState !== 4) return;
    
                // Process the response
                if (xhr.status >= 200 && xhr.status < 300) {
                    // If successful
                    var data = JSON.parse(xhr.responseText).data;
                    var gif = {
                        url: data.fixed_width_downsampled_url,
                        sourceUrl: data.url
                    };
                    resolve(gif);
                } else {
                    // If failed
                    reject({
                        status: request.status,
                        statusText: request.statusText
                    });
                }
    
            };
            xhr.open('GET', url);
            xhr.send();
      });
    
    }
    

    Need to invoke method depends on signature of function.

    getGif(searchText).then((response)=>{
       console.log(response);
    }, (error)=> { 
      console.log(error);
    })
    
    评论

报告相同问题?

悬赏问题

  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常