Martin AJ
Martin AJ

Reputation: 6697

How can I use a variable as a function?

Here is my code:

Promise.all([twitter_ajax(), instagram_ajax(), facebook_ajax()]).then(() => {
    stopBlinking()
    formSubmited = false;
}).catch( (err) => {
    console.error(err);
    stopBlinking()
    formSubmited = false;
})

Since I have a setting system in my project, I need to make those three ajax requests dynamic. I mean sometimes I need to send all of them, other times I need to send both of those, or probably one of them. It's all depend on the setting configured by user.

Any idea how can I handle that?


Here is my idea which has syntax error. I store the setting into cookie and can access it like this:

var functions = getCookie($ajaxRequests);
//=> twitter_ajax(), instagram_ajax(), facebook_ajax()

See? I have a string of a part of my code. But sadly this doesn't work:

Promise.all([ functions ]){ ... }

Upvotes: 0

Views: 56

Answers (2)

Salketer
Salketer

Reputation: 15711

I'll consider that the functions are stored globally (on window) as your code does not show any scope, you might need to replace window with the appropriate object. The idea is to use brackets [] to be able to access methods or properties using variable values, strings or strings containing non-normal characters such as full stop .

var settings = ["twitter_ajax","instagram_ajax"];
var promises = settings.map(function(func_name){
    return window[func_name](); //Change window to what is appropriate if necessary.
})
Promise.all(promises).then(() => {
    stopBlinking()
    formSubmited = false;
}).catch( (err) => {
    console.error(err);
    stopBlinking()
    formSubmited = false;
})

So, we use map to execute the function names for each array entry, and return an array of their return values (promises).

A very interesting post (almost duplicate of yours) about using variables content to call function.

Upvotes: 2

Jonas Wilms
Jonas Wilms

Reputation: 138235

You can have non-promise values in the array which count as resolved. Therefore the best would probably be terminating the functions early:

function twitter_ajax(){
 //if settings are wrong
 if( !load_twitter ) return;
 //elsewhen call and return a promise
 return Promise.resolve();
}

Or you load them conditionally in Promise.all:

Promise.all([
  load_twitter? twitter_ajax() : 0,
  load_facebook? facebook_ajax() : 0
]).then(whatever);

Upvotes: 2

Related Questions