0

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();
    },
Sofyan Thayf
  • 1,322
  • 2
  • 14
  • 26
cruznovsky
  • 11
  • 2
  • 2
    Possible duplicate of [How do I convert an existing callback API to promises?](https://stackoverflow.com/questions/22519784/how-do-i-convert-an-existing-callback-api-to-promises) – George Oct 13 '19 at 11:46
  • @George can you show me how it works on my code? – cruznovsky Oct 13 '19 at 12:12

1 Answers1

0

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);
})
Prashant Biradar
  • 301
  • 5
  • 14