How to execute a Javascript function only after multiple other functions have completed?

后端 未结 7 1995
轻奢々
轻奢々 2020-12-25 15:03

My specific problem is that I need to execute a (potentially) large number of Javascript functions to prepare something like a batch file (each function call adds some infor

相关标签:
7条回答
  • 2020-12-25 16:01

    I was looking for the same kind of pattern. I am using APIs that interrogate multiple remote data sources. The APIs each require that I pass a callback function to them. This means that I cannot just fire off a set of my own functions and wait for them to return. Instead I need a solution that works with a set of callbacks that might be called in any order depending on how responsive the different data sources are.

    I came up with the following solution. JS is way down the list of languages that I am most familiar with, so this may not be a very JS idiom.

    function getCallbackCreator( number_of_data_callbacks, final_callback ) {
    
        var all_data = {}
    
        return function ( data_key ) {
    
            return function( data_value ) {
                all_data[data_key] = data_value;
    
                if ( Object.keys(all_data).length == number_of_data_callbacks ) {
                    final_callback( all_data );
                }
            }
        }
    }
    
    var getCallback = getCallbackCreator( 2, inflatePage );
    
    myGoogleDataFetcher( getCallback( 'google' ) );
    myCartoDataFetcher( getCallback( 'cartodb' ) );
    

    Edit: The question was tagged with node.js but the OP said, "I'm looking for a general Javascript programming pattern for this," so I have posted this even though I am not using node.

    0 讨论(0)
提交回复
热议问题