0

I am trying to implement an asynchronous function in my code and finally got it to actually wait properly, however, after waiting it seems to just stop.

function onLoad() {
    fillTechOptions();
}

function getData() {
    return new Promise(resolve => {
    // var XMLHttpReqeust = require("xmlhttprequest").XMLHttpReqeust;
    xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function() {
        if ( xhr.readyState == xhr.DONE && xhr.status == 200 ) {
            var dataset = xhr.responseText
            dataset = JSON.parse(dataset);
            console.log(dataset.recordset);
            data2 = dataset.recordset;
            
        }
        // if (xhr.readyState == 2){
            // xhr.responseType = 'json';
        // }
    };
    xhr.open('GET', 'http:localhost:5000/data', true);
    xhr.withCredentials = false;

    xhr.send();
    });
}

async function fillTechOptions() {
    alert("ran function");
    await getData();
    alert("continuing");
    var techSkills = ['All Skills'];
    for(var x = 0; x < data2; x++){
        techSkills.push(data2.SkillName);
    };
    select = document.getElementById('techSkillsSelectID');

    for (var i = 0; i<techSkills; i++){
        var opt = document.createElement('option');
        opt.value = techSkills[i];
        opt.innerHTML = techSkills[i];
        select.appendChild(opt);
    };
}

onload() runs once the HTML body loads, which calls the function that is supposed to wait. I get the first alert that the function runs, then a second later my dataset appears in the console, then it just stops. I never get the second alert. Any ideas why this is happening?

2 Answers2

0

You need to resolve the promise by calling resolve for the async action (getData) to be marked as completed (or reject if something went wrong)

varoons
  • 3,807
  • 1
  • 16
  • 20
0

For promises you need to call resolve or reject to let the promise know if it failed or succeeded

new Promise((resolve, reject) => {

  xhr.onreadystatechange = function() {
    if (xhr.readyState == xhr.DONE) {
      if (xhr.status == 200) {
        var dataset = xhr.responseText
        dataset = JSON.parse(dataset);
        console.log(dataset.recordset);

        resolve(dataset.recordset);
      } else {
        //  You can deal with errors here
        reject();
      }
    }
  };

});
Kenneth Truong
  • 3,882
  • 3
  • 28
  • 47