gpt4 book ai didi

javascript - 如何将匿名函数初始化为变量并稍后使用它?

转载 作者:行者123 更新时间:2023-12-01 03:01:50 25 4
gpt4 key购买 nike

这是我的代码:

Promise.all([
ajaxRequest(value, 'search/twitter', 'twitter').then(
function(res) {
var imgStatus = res[1].length > 0 ? "successfully.png" : "noRes.png";
$('.option_name_twitter + td').html("<img src='img/" + imgStatus + "' />")

optionsRes['twitter'] = res[1];
$('input.twitter').show();

}, function(err){
console.log(err);
$('.option_name_twitter + td').html("<img src='img/warning.png' />")
}
),
ajaxRequest(value, 'search/instagram', 'instagram').then(
function(res) {
var imgStatus = res[1].length > 0 ? "successfully.png" : "noRes.png";
$('.option_name_instagram + td').html("<img src='img/" + imgStatus + "' />")

optionsRes['instagram'] = res[1];
$('input.instagram').show();

}, function(err){
$('.option_name_instagram + td').html("<img src='img/warning.png' />")
}
)
]).then(() => {
stopBlinking()
formSubmited = false;
}).catch( (err) => {
console.error(err);
stopBlinking()
formSubmited = false;
})

如您所见,我在 promise.all() 方法中有两个函数。有时我只需要单独调用其中一个函数。像这样的事情:

$("input.twitter").on('click', function(){
// only the first function should be called here
})

$("input.instagram").on('click', function(){
// only the second function should be called here
})

这些^将在Promise.all()执行一次后被调用。因为 input.twitterinput.instagram 最初都是隐藏的,在调用 Promise.all() 后才会显示。

所以我想将这些匿名函数(存在于 promise.all() 中)初始化为变量,并在单击 input.instagraminput.twitter。我怎样才能做到这一点?

最佳答案

只是将代码放在两个函数中?

function searchTwitter() { // maybe specify `value` as argument
return ajaxRequest(value, 'search/twitter', 'twitter').then(...);
}

function searchInstagram() {
return ajaxRequest(value, 'search/instagram', 'instagram').then(...);
}

Promise.all([searchTwitter(), searchInstagram()]).then(...);
// and whenever you want:
searchTwitter().then(...);
searchInstagram().then(...);

您可以learn more about functions in Eloquent JavaScript .

关于javascript - 如何将匿名函数初始化为变量并稍后使用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46398429/

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