-1

Okay, so I've almost got the hang of promises.

I'm trying to figure out how to place a promise within view_functions so that the return works.

function loadViewFunctions(view_functions,append_data){

    var this_app_data = [];

    function viewFunctions(){

        for (i = 0; i < view_functions.length; i++) {

            this_app_data[i] = window[view_functions[i]]();

        }
        for (i = 0; i < this_app_data.length; i++) {

            this_app_data[i].then(function(this_d) {

                append_data = append_data + this_d;

            });
        }
        return append_data;
    }

    //return
    return viewFunctions().then(post_app_data => {
        return post_app_data;
    });
};

1 Answers1

0

The following snippet should be equivalent to what I think you are trying to achieve:

function loadViewFunctions (view_functions, initial_append_data) {
  // retrieve the functions and calls them
  const promises = view_functions.map(f => window[f]());
  return Promise.all(promises).then(
    // join the results together
    results => results.reduce((acc, this_d) => acc + this_d), initial_append_data)
  );
}

It uses

  • map to iterate over an array and create a new one and
  • Promise.all to wait until all promises that you give to it have resolved

As others have mentioned in the comments, don't use function names to access global functions. Pass an array of functions instead.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
PeterMader
  • 6,987
  • 1
  • 21
  • 31