Probably a good circumstance where an async function might work better. I generally find async functions work better when everything needs to execute in a specific order.
Depending on how the service works it’s also probably worth returning promises from your backend.
// As much as I'm a fan of code reusability maybe reconsider how many functions you're calling here.
// Unless you're using the functions repeatedly elsewhere it might not be worth breaking it up so much.
addMessageToConversation(conversationId: string, message: string): Promise<any> {
return new Promise(async (resolve) => {
await this.getConversationToAddMessage(conversationId).messages.push(this.createMessage(message));
resolve();
});
}
getConversationToAddMessage(id: string): Promise<any> {
return new Promise((resolve) => {
resolve(this._conversations.getValue().find(conversation => conversation.id === id));
});
}
private createMessage(message: string): Message {
return {
id: Math.random().toString(), // For truly unique IDs you should use some kind of timestamp based seed. Although random, random numbers can appear more than once.
text: message,
userId: this.authService.userId,
timestamp: new Date(Date.now())
}
}