Currently encountering a common issue involving asynchronous execution, state management, and indentation complexities.
Imagine a scenario where a REST call is made to add user information (user_info
) to a user, notify their contacts of the change, and return the updated user information in the response. However, the user object
only contains the IDs of the user_info
objects through a 1 to n relation.
Sequence of Calls:
request -> saveUserInfo -> updateUser -> notifyContacts -> response
Functions saveToDb
, updateUser
, and notifyContacts
are asynchronous and cannot be easily composed due to different inputs, outputs, and execution order dependencies.
Below are simplified function headers:
function saveUserInfo(payload): Promise<UserInfo[]> { /*...*/ }
function updateUser(user_id, user_infos): Promise<User> { /*...*/ }
function sendNotification(user, user_infos): Promise<void> { /*...*/ }
While working on the request handler, I relied heavily on mergeMap
to subscribe to inner observables for asynchronous actions. Here's an example:
function handleRequest(payload, user_id) {
return saveUserInfo(payload).pipe(
mergeMap(user_infos =>
from(updateUser(user_id, user_infos)).pipe(
mergeMap(user =>
from(notifyContacts(user, user_infos)).pipe(map(() => user_infos))
)
)
)
)
}
Not entirely satisfied with this approach, as it may become complex with additional logic in the future. Explored RxJS documentation but could not find a more elegant solution to chain these asynchronous calls. The challenge lies in articulating the problem concisely, prompting this inquiry.
Any suggestions for a better solution? Seeking a pure RxJS approach, preferably without helper functions.