Avoid Diamond Problem in JavaScript by anti patterns.

Most of the time when our code required non-blocking code, we get into traditional diamond problem when each .then() block is nested inside other .then() block. These type code sometime becomes to complex that debugging and error handling becomes too difficult for the developer in later stage of the development or while solving the bug in the code.

// final check

Please see the above code. This is a traditional approach which has nested methods and which may have a dependency of variables res, res2, res3 and so on. In the example there are only 4 methods but practically there can be lots of methods which are nested inside. This is called as a typical diamond problem because of the shape of the code. In such code, it is difficult to manage or update the code in later stage and also if one of the promise is not resolve properly or threw any error then logging that error is little bit hard.

Be there is a good solution to over come this problem which is called as anti-pattern. By this pattern, instead of calling the method inside .then(), we just have to return the promise. Please see the below code.

method1.then((res)=>{return method2();}).then((res2)=>{return method3();}).then((res3)=>{return method4();}).then((res4)=>{//final check}).catch((err)=>{   // final check

In the above code, we are achieving the same functionality as we are doing it in code snippet 1, but the difference here is, we are free from the diamond problem. In the above code, each method is returning a Promise and there is .then() method for each of that returned promise.

The advantage here is that we are free from diamond problem and error handling is also done in a better way. See the last catch block, this catch block will execute when any of the above method ‘rejects’ the promise or throws any error.

The only disadvantage of this pattern is, we cannot access variables of each .then() block in other .then() block as those variables’ scope is limited to that code block, but we can overcome this with local variables at the start of the method.