Learn, Share, Build

249
September 27, 2017, at 11:52 AM

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 ]){ ... }
Answer 1

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

Rent Charter Buses Company
READ ALSO
Learn, Share, Build

Learn, Share, Build

I have a bootstrap code belowWhen the button is clicked, the modal is showing correctly

214
Learn, Share, Build

Learn, Share, Build

I have a form where I set textarea field id by for loop using php

265
Learn, Share, Build

Learn, Share, Build

I am using bootstrap datatableI want to add custom filter with bootstrap datepicker

232
Learn, Share, Build

Learn, Share, Build

so I tried making a simple on change fiddleI can't get it to work

263