0

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 ]){ ... }
Martin AJ
  • 6,261
  • 8
  • 53
  • 111

2 Answers2

2

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);
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
2

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.

Salketer
  • 14,263
  • 2
  • 30
  • 58
  • 1
    Why not e.g. `settings.push( twitter_ajax )` and then `promises = settings.map(f=>f())` – Jonas Wilms Sep 27 '17 at 06:14
  • I extrapolated that the settings were coming from a text source, since OP gets them from getCookie(). So my proposition skips the step of checking text value and adding the related function. Although this also means a malicious user could add any function name and make them run, so a filter of some sort would be required anyways. – Salketer Sep 27 '17 at 10:38