I am trying to fix some code that is really Promise heavy I am trying to fix is by removing the new Promise declaration and returning the initial Promise instead, but am trying to make sure that I am properly tanslating the before and after. Below I have an example outlining one of the scenarios that need to be changed. Am I missing something between the before and after code or am I traveling in the right direction? Also,for the after, will I be able to catch all of the rejected errors?
Before:
add(book: IBook, authorId: string): Promise<IBookModel> {
let p = new Promise((reject, resolve) => {
let newBook: IBook = new Book({…book});
newBook.createInitialSetup();
let bookReady = {... newBook};
this.bookRepository.add(bookReady)
.then((completedBook: IBookModel) => {
this.bookRepository.findAuthorById(authorId)
.then((author: IAuthorModel) => {
let newBookAuthor: IAuthorModel = new Author();
newBookAuthor(completedBook._id, author._id);
let finalBookAuthor = {... newBookAuthor} as IAuthor;
this.bookRepository.addBookAuthor(finalBookAuthor)
.then((result: IBookAuthorModel) => {
resolve(completedBook);
})
.catch((err: Error) => {
reject(err);
});
})
.catch((err: Error) => {
reject(err);
});
})
.catch((err: Error) => {
reject(err);
});
});
return p;
}
After:
add(book: IBook, authorId: string): Promise<IBookModel> {
let groupSetup: IGroupModel = new Group({...group});
newBook.createInitialSetup();
let bookReady = {... newBook};
return this.bookRepository.add(bookReady)
.then((completedBook: IBookModel) => {
return this.bookRepository.findAuthorById(authorId)
.then((author: IAuthorModel) => {
let newBookAuthor: IAuthorModel = new Author();
newBookAuthor(completedBook._id, author._id);
let finalBookAuthor = {... newBookAuthor} as IAuthor;
return this.bookRepository.addBookAuthor(finalBookAuthor)
.then((result: IBookAuthorModel) => {
return completedBook;
});
});
});
}