I've created a for_users
function that retrieves an array of users from a web service, applies a specified function f
to each user in the array, and then triggers a callback function f_then
.
// Apply f to each user, then trigger f_then.
function for_users(f, f_then)
{
// Retrieve all users from the database and store them in user_array
db.get_all_users(function(user_array)
{
// Apply f to each user
user_array.forEach(f);
// Call the continuation callback
f_then();
});
}
When using the for_users
function with an asynchronous function as the parameter for f
, I want all the f
callbacks to complete before calling f_then
. However, this isn't happening in the current setup because user_array.forEach(f)
doesn't wait for f
to finish before moving on to the next iteration.
Let's consider a problematic scenario:
function example_usage()
{
var temp_credentials = [];
for_users(function(user)
{
// The get_credentials function is asynchronous and will
// invoke the provided callback after fetching credentials
// from the database
database.get_credentials(user.ID, function(credential)
{
// ...
});
}, function()
{
// The do_something call happens before all callbacks are
// completed (potentially)
// temp_credentials may be empty at this point!
do_something(temp_credentials);
});
}
How can I modify the for_users
function so that if f
is asynchronous, f_then
is only triggered when all f
functions have finished?
Sometimes, however, the provided f
function for for_users
is synchronous and the existing implementation might work. Is there a way to create a generic for_users
function that accommodates both asynchronous and synchronous f
functions?