有条件的承诺

Chr*_*phe 6 javascript ajax promise

在我的脚本中,我需要检索字典以将编码值转换为名称:

$.ajax({
    // retrieve dictionary
})
.done(function(dictionary){
    // convert encoded values into names
})
.done(function(){
    // run my application
});
Run Code Online (Sandbox Code Playgroud)

但是,有时字典已经被另一个应用程序加载,在这种情况下我不需要ajax调用:

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
});
}
Run Code Online (Sandbox Code Playgroud)

这个if/else语句相当重,是否有办法缩短它:

// load dictionary if needed
// then run my application
Run Code Online (Sandbox Code Playgroud)

注意:我使用$ sign作为我的伪代码,但我不一定与jQuery绑定.

sie*_*iej 1

也许用 $.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
    });
Run Code Online (Sandbox Code Playgroud)