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

标签 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。我怎样才能做到这一点?

最佳答案

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

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/

相关文章:

javascript - 设置超时函数

Javascript 显示/隐藏

javascript - 如何右对齐 ExtJS tbar 的内容?

javascript - 如何通过javascript在浏览器中显示python输出?

javascript - 仅显示 div 的事件处理程序

php - 检查数字是否为十进制

javascript - 警告 : There is another module with an equal name when case is ignored

javascript - 从 HTML 表中导出记录的最佳实践

javascript - 从 HTML 中查找数据值

javascript - 如何修复 Javascript 函数参数(当我使用变量传递参数时)