在我的剧本,我需要检索字典来转换EN codeD值成名字:
In my script, I need to retrieve a dictionary to convert encoded values into names:
$.ajax({
// retrieve dictionary
})
.done(function(dictionary){
// convert encoded values into names
})
.done(function(){
// run my application
});
不过,有时字典已加载另一个应用程序,在这种情况下,我不需要Ajax调用:
However, sometimes the dictionary has already been loaded by another application, and in this case I don't need the ajax call:
if (dictionary) {
// convert encoded values into names
// run my application
}
else {
$.ajax({
// retrieve dictionary
})
.done(function(dictionary){
// convert encoded values into names
})
.done(function(){
// run my application
});
}
这if / else语句是相当重的,有没有办法把它缩短:
This if/else statement is rather heavy, is there a way to make it shorter:
// load dictionary if needed
// then run my application
注:我用$符号为我的假code,但我不必拘泥于jQuery的
Note: I used the $ sign for my pseudo-code, but I am not necessarily tied to jQuery.
也许创建$。当一个假的承诺?
Maybe create a bogus promise with $.when?
var promise;
if (dictionary) promise = $.when(dictionary);
else {
promise = $.ajax({
})
.done(function(dictionary){
// convert encoded values into names
});
}
promise
.done(function(){
// run my application
});