有条件的承诺 [英] Conditional promises
本文介绍了有条件的承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的剧本,我需要检索字典来转换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
});
这篇关于有条件的承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文