JavaScript Promises 未按正确顺序执行
2021-05-07
62
我遇到了一个问题。我正在尝试执行以下操作:
我首先检查 URL 中是否包含
agentId
参数。然后我想在我的数据库中检查给定的
agentId
是否属于有效代理。如果是,那么我想将该代理的整个对象存储在名为
selectedAgent
的变量中。然后我想在我的下 2 个函数中使用
selectedAgent
。
问题是它给了我错误:
Uncaught TypeError: Cannot read property 'active' of null
在第 106 行。这是因为链中的最后一个函数先于其余函数执行。这是代码:
const urlString = window.location.search;
const urlParams = new URLSearchParams(urlString);
let selectedAgentId = urlParams.get('agentId');
let selectedAgent = null;
document.addEventListener('DOMContentLoaded', function(event) {
getStartupAgentData().then(fillAgentComboBox()).then(setToggleButtonContent());
});
function getStartupAgentData() {
return new Promise(function(resolve, reject) {
$.ajax({
type: 'POST',
url: 'overview_get_agent_ajax.php',
data: 'agentid=' + selectedAgentId,
dataType: 'text',
success: function(data) {
selectedAgent = JSON.parse(data)[0];
console.log(selectedAgent);
resolve(true);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("Failed receiving agents")
reject(true);
}
});
});
}
function fillAgentComboBox() {
console.log(selectedAgent);
return new Promise(function(resolve, reject) {
getAllAgentData().then(function(agents) {
let comboBoxAgent = document.getElementById("comboBoxAgent");
for (let i = 0; i < agents.length; i++) {
let option = document.createElement("option");
// Agent data
let id = agents[i].id;
let owner = agents[i].owner;
let exchange = agents[i].exchange;
let remark = agents[i].remark;
let text = "Agent " + id.toString().padStart(4, "0") + " - " + owner + " - " + exchange + " - " + remark;
option.text = text;
option.value = id;
comboBoxAgent.add(option);
if (selectedAgent === null) {
option.selected = true;
selectedAgent = agents[i];
}
else if (id === selectedAgentId) {
option.selected = true;
selectedAgent = agents[i];
}
}
// Add agent id to url for other javascripts
window.history.replaceState(null, null, "?agentId=" + selectedAgent.id);
resolve(true);
});
});
}
function getAllAgentData() {
return new Promise(function(resolve, reject) {
$.ajax({
type: 'POST',
url: 'overview_get_agents_ajax.php',
data: '',
dataType: 'text',
success: function(data) {
resolve(JSON.parse(data));
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
reject(true);
}
});
});
}
function setToggleButtonContent() {
let btnToggleAgent = document.getElementById("btnToggleAgent");
if (selectedAgent.active == true) {
btnToggleAgent.style.background = "#EE4141";
btnToggleAgent.innerHTML = "Stop";
}
else {
btnToggleAgent.style.background = "#44B642";
btnToggleAgent.innerHTML = "Start";
}
}
我该如何解决这个问题?
2个回答
您需要
then(fillAgentComboBox)
,而不使用
()
,后者会就地调用您的函数并立即启动。您也可以执行
then(() => fillAgentComboBox())
Andy Ray
2021-05-07
将函数传递给
.then
,而不是调用它们并传递它们的返回值。
getStartupAgentData().then(fillAgentComboBox).then(setToggleButtonContent);
Unmitigated
2021-05-07