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

时间:2017-09-25 05:54:34

标签: javascript jquery function

这是我的代码:

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时使用它们。我怎么能这样做?

1 个答案:

答案 0 :(得分:2)

只需将代码放在两个函数中即可?

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