gpt4 book ai didi

javascript - 有条件的 promise

转载 作者:数据小太阳 更新时间:2023-10-29 05:23:08 24 4
gpt4 key购买 nike

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

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

但是,有时字典已经被另一个应用程序加载,在这种情况下我不需要 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
});
}

这个 if/else 语句比较重,有没有办法让它更短:

// load dictionary if needed
// then run my application

注意:我在我的伪代码中使用了 $ 符号,但我不一定依赖于 jQuery。

最佳答案

您应该恰好调用一次 $.ajax(),并将返回的 promise 存储在您的(全局)字典 变量中。

然后,每次要使用结果时,只需编写dictionary.then(...)即可。
如果 AJAX 请求已经完成,回调将立即运行。

关于javascript - 有条件的 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19099522/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com