Are nested promises a good practice?

Viewed 388

Short description of the application and why I am having the problem

I am making a website with express/Apollo API server. I want to isolate the use-cases and the resolver for the Apollo server.

So I made three classes, one class named createTender in the entity folder, a second class, the handler, which formats the data so the createTender only gets the data it needs. The third class is the dataBaseGatway the middle man for the application and the database.

basic diagram of the classes

I did not include the dataBase or the mongoose module in the diagram.

Here is the scenario for the question

In one instance, I need to create a table in the database, and I need to await the function that will create that table. But the function that i call from the resolver(where the API request is handled) calls another function that handles the creation of the table, then saves it to MongoDB and checks for errors. This function is async/await, it awaits for the new table to be saved.

Here is the question

Are nested promises a good practice?

Is there something wrong with creating promise that has promise inside it?

And what about a promise inside a promise inside a promise?

1 Answers

Nested promises are an unfortunate side-effect of the red-blue function split in javascript. That is, once you start adding async functions, you're pretty much stuck in that paradigm. What will define if its good practice or bad practice is how your organize your code to make it easy to reason about. The core things that can make promises confusing is not properly documenting return values, and not explicitly blocking for promise resolution with things like Promise.all.

In broad terms, I think async-await is a better pattern that does the same thing and makes it easier to reason about the code, but there are times when promises are more immediately useful.

Also important: with a chain of promises, you should consider .finally to clean up logic in cases where things go south.

Related