JavaScript How to Convert Callback to Promise

I finally finished upgrading my travel website to use Promises instead of callbacks.

It was fairly straightforward.

This is an example of the callback:

 

function hasacallback(param1, callbackFunction) {
    var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
     callbackFunction(this.responseText);
    }
  };
  xhttp.open(“GET”, “ajax_info.txt”, true);
  xhttp.send();
}

function makeacall() {
    var callback = function() {
        console.log(‘All done’);
    }

    hasacallback(‘abc’, callback);
}

makeacall();

This is how the above would be updated to use Promises:

 

function usespromise(param1) {
    return new Promise((resolve, reject) => {
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                resolve(this.responseText);
             }
        };
        xhttp.open(“GET”, “ajax_info.txt”, true);
        xhttp.send();
    });
}

function makeacall() {
    var callback = function() {
        console.log(‘All done’);
    }

    usespromise(‘abc’)
    .then((result) => {
       callback();
    });
}

makeacall();

(paid links)

Learn JavaScript