Adalast
Adalast

Reputation: 161

JS Async/Await isn't working in combination with forEach

Here is the code I'm working with (IP address censored for obvious reasons):

async function buildJobsView() {
    let jobList = await getJobs()
    Promise.all([getJobs()]).then($("#jobsPane").text(jobList))
}

async function getJobs() {
    //Open API connection and submit
    var url = "http://IPADDRESS:8082/api/jobs?IdOnly=true"
    var xhr = new XMLHttpRequest()
    xhr.open("GET", url, true)
    xhr.send()
    xhr.onreadystatechange = function() {
        if(xhr.readyState == 4 && xhr.status == "200") {
            return xhr.response
        }
    }
}

For whatever reason, the jobList variable is being assigned before the getJobs() function finishes running. The getJobs() function does return the right output eventually, but the code has already moved on. What am I doing wrong?

Upvotes: 1

Views: 64

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370759

async doesn't automatically convert callback-based code into Promise-based code - you have to explicitly convert the callback to a Promise and return a Promise whenever you want to be able to use it as a Promise.

function getJobs() {
  return new Promise((resolve) => {
    //Open API connection and submit
    var url = "http://IPADDRESS:8082/api/jobs?IdOnly=true"
    var xhr = new XMLHttpRequest()
    xhr.open("GET", url, true)
    xhr.send()
    xhr.onreadystatechange = function() {
      if(xhr.readyState == 4 && xhr.status == "200") {
        resolve(xhr.response)
      }
    }
  });
}

Then, getJobs will return a Promise, and then you can consume it with await:

const jobList = await getJobs()

Upvotes: 2

Related Questions