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);
    })
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Arduino,利用modbus的RS485协议,进行对外置的温湿度传感器进行数据读取
  • ¥15 vhdl+MODELSIM
  • ¥20 simulink中怎么使用solve函数?
  • ¥30 dspbuilder中使用signalcompiler时报错Error during compilation: Fitter failed,求解决办法
  • ¥15 gwas 分析-数据质控之过滤稀有突变中出现的问题
  • ¥15 没有注册类 (异常来自 HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))
  • ¥15 知识蒸馏实战博客问题
  • ¥15 用PLC设计纸袋糊底机送料系统
  • ¥15 simulink仿真中dtc控制永磁同步电机如何控制开关频率
  • ¥15 用C语言输入方程怎么