1.逻辑混乱的代码:
function attach (node, status, done) {
node.addEventListener('click', function () {
var id = node.dataset.id;
var endpoint = '/api/v1/records/' + id;
http.get(endpoint, function (res) {
node.innerHTML = res.data.view;
reportStatus(res.status, function () {
done(res);
});
});
function reportStatus (status, then) {
status.innerHTML = 'Status: ' + status;
then();
}
});
}
attach(record, status, function (res) {
console.log(res);
});
2. 重构之后
function attach (node, status, done) {
function handler () {
var id = node.dataset.id;
var endpoint = '/api/v1/records/' + id;
http.get(endpoint, update);
}
function update (res) {
node.innerHTML = res.data.view;
status.innerHTML = 'Status: ' + res.status;
done(res);
}
node.addEventListener('click', handler);
}
attach(record, status, function (res) {
console.log(res);
});
1. 为匿名函数命名
2.去掉不必要的回调
3.在流程控制代码中使用条件语句要小心