簡體   English   中英

如何將匿名函數初始化為變量並在以后使用?

[英]How can I initial an anonymous function into a variable and use it later?

這是我的代碼:

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()

因此,我想將那些匿名函數(存在於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(...);

您可以了解有關Eloquent JavaScript中的函數的更多信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM