简体   繁体   中英

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

Here is my code:

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;
})

As you see I have two functions into promise.all() method. Sometimes I need to call only one of those function separately. Something like this:

$("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
})

These ^ will be called after when Promise.all() is executed once. Because both input.twitter and input.instagram are hidden at first and will be shown after Promise.all() call.

So I want to initial those anonymous functions (which are exist at promise.all() ) into variables, and use them on click of input.instagram and input.twitter . How can I do that?

Just put the code in two functions?

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

You can learn more about functions in Eloquent JavaScript .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM