编辑,看起来我错过了问题中的一个细节......
因此,您要做的是异步串行执行操作。
这是可重用的东西:
series([
function(callback) {
if ( rowChanged && upOk ) {
jQuery('#save_btn').prop('disabled', true);
formmodified = false;
actionArray(updateArray, 'update', callback);
} else {
callback();
}
},
function(callback) {
if ( rowChanged && saveOk ){
jQuery('#save_btn').prop('disabled', true);
formmodified = false;
actionArray(saveArray, 'save', callback);
} else {
callback();
}
}
],fn);
function series(taskList,done) {
var next = taskList.shift();
if ( typeof next === 'function' ) {
next(series.bind(this,taskList,done));
} else if ( typeof done === 'function' ) {
done();
}
}
...这是一个模拟版本,全部拼写出来(用超时来表示异步任务):
// first create the task list
var tasks = [
function one(callback) { // this is a "medium" difficulty task
console.log('one',new Date()); // so you can see some output
setTimeout(callback,1000); // return callback after 1 second (async)
},
function two(callback) { // this is a "hard" difficulty task
console.log('two',new Date()); // more output
if ( true ) { // after some initial logic
setTimeout(function() { // and then an async task for 500ms
if ( true ) { // and more logic later
callback(); // issue the callback
}
},500);
}
},
function three(callback) { // this is an easy task
console.log('three',new Date());
callback(); // return callback right away
}
];
// `series` will handle moving the task list along
function series(taskList,done) {
var next = taskList.shift(); // get the next function to call
if ( typeof next === 'function' ) { // if there is one, and it is a function
next(series.bind(this,taskList,done)); // execute it, and pass it the callback for the next task
} else if ( typeof done === 'function' ) { // if there isn't another task, but there's a done function
done(); // call the complete function, this is guaranteed to fire, if defined
}
}
series(
tasks.slice(0), // make a copy of tasks to save for later (if you want)
function complete() { // complete will be called when the tasks have run out
console.log('complete!',new Date());
}
);
//series(tasks); // alternatively, w/o the copy `.slice(0)` tasks will be depleted when it is done
老的:
只需继续嵌套 lambda:
function addFunction(fn) {
if (rowChanged && upOk) {
jQuery("#save_btn").prop('disabled', true);
formmodified = false;
actionArray(updateArray, "update", function() {
if (rowChanged && saveOk) {
jQuery("#save_btn").prop('disabled', true);
formmodified = false;
actionArray(saveArray, "save", fn);
}
});
}
}
非常丑陋,但很典型,直到您开始真正组织代码和/或使用库(例如async)。