I want to share data between the two concurrent method calls shown below.
async generateSuggestedSparks(userId: GraphID, friends: Person[], latLng: LatLng) {
let suggestions = await this.generateAndMergeListsInParallel([
this.generateHardCodedSparks(userId, friends, latLng),
this.generateRandomActivitySparks(userId, friends, latLng, 6),
]);
suggestions = this.filterDuplicateSuggestions(suggestions);
return suggestions.slice(0, 7);
}
async generateAndMergeListsInParallel<T>(promises: Promise<T[]>[]): Promise<T[]> {
let lists = await Promise.all(promises);
return lists.flat();
}
Each method generates a number of artifacts for a randomly selected subset of friends. In both methods, I remove selected friends from the friends list to avoid selecting the same friend multiple times. I would like to generalize this logic to share data across the two concurrent promises to avoid one choosing a friend already used in the other.
What is the canonical way to share data across the concurrently running methods in NodeJS?
2
Answers
JavaScript is a single-threaded language, it does not support or handle parallel requests natively. You will have to use some other framework to do the parallel processing. even with promises, the methods get executed one by one.
There is a problem with premises presented in the question that may impede answering regardless of the expected nature of a solution: promises are passive objects, they are not executed, and hence they never "run". Promises either exist or have become eligible for memory garbage collection.
What promises are is a combination of
setTimeout
: promises don’t use elapsed time to become settled and instead generalise asynchronous processing by using user calls to theirresolve
andreject
functions to set the value and status of a promise’s datum – or link it to the result of another promise ifresolve
is passed a promise-like object.While many questions have been asked about "I don’t understand why these promises became fulfilled in an order that I didn’t expect", the reality is that such questions are theoretical: promises were designed to solve the problem that in general the time of completion of asynchronous operations is unpredictable.
The canonical answer to how to work around problems caused by by waiting for promise settlement in parallel is to no use
Promise.all
– wait for promise supply of data that impacts later promises in a chain by creating the promises in a chain.Note that Promise handling of data base access results will not provide data base request optimization that may or may not be available by combining multiple RDMS queries into one.