【发布时间】:2019-07-07 17:39:33
【问题描述】:
我正在尝试在我的代码中实现一个异步函数,并最终让它真正正确地等待,但是,在等待之后它似乎就停止了。
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() 在 HTML 主体加载后运行,它调用应该等待的函数。我收到函数运行的第一个警报,然后一秒钟后我的数据集出现在控制台中,然后它就停止了。我从来没有收到第二个警报。任何想法为什么会发生这种情况?
【问题讨论】:
-
可能是因为
resolve没有在getData()中调用?尝试在onreadystatechange处理程序中添加resolve()。 -
@SunnyPun 做到了。谢谢!