JS Async / Await与forEach不兼容

问题描述 投票:1回答:1

这是我正在使用的代码(由于显而易见的原因,IP地址被删除):

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
        }
    }
}

无论出于何种原因,jobList变量在getJobs()函数完成运行之前被赋值。 getJobs()函数最终会返回正确的输出,但代码已经移动了。我究竟做错了什么?

javascript asynchronous async-await
1个回答
2
投票

async不会自动将基于回调的代码转换为基于Promise的代码 - 只要您希望能够将其用作Promise,就必须将回调显式转换为Promise并返回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)
      }
    }
  });
}

然后,getJobs将返回一个Promise,然后你可以用await消费它:

const jobList = await getJobs()
© www.soinside.com 2019 - 2024. All rights reserved.