Callbacks for try


Callbacks is one of oldest patterns and has helped many projects excel and cause a lot of traction to the software community as a whole. I had heard about it in one of my roles but rarley got the chance to explore or understand it until lately. It was to my surprise I found that having to use that makes the programmer not do one additional step, guess what?
Let's look at a sample method to run a SQL query method called execute
in a popular library.
The execute accepts the first argument as the query to be run, the next argument to be a method ( referred to as name callback ) accepting two or exactly three arguments. The first one is the error
, and the next is the result
or let's say an array of rows from a select
query.
When calling this method execute
, the user can call it like below
function getRows() {
database.execute("SELECT * FROM tableA LIMIT 10;", (err, rows) => {
if(err)
return err;
return rows;
});
}
The getRows
method returns the rows if no issue running the SQL statement, otherwise it returns the error object from the execute
method.
Let's say the database service is gone done for a bit. If the method is run at that moment, the execute
method sets the err
to the error object or similar and the rows
to null ( err and rows need not be the same name ).
Curios enough one may wonder how would this look like in the execute
method.
The `execute method more or less will look like below.
function execute(query, callbk) {
mainDb.run(query).then(res => callbk(null, res)).catch(err => callbk(err, null));
}
Here, the run
makes use of the Promise
callback or is an async
method. Refer to MDN docs for more information.
What benefit have we achievied doing this?
Yes, we need to understand to reason for the callback use. If we look carefully we are segrating the one return value into atleast two. One for success when the rows are returned. The other for all other error cases. By doing so we can almost completely avoid making use of the try - catch
block completely. Do you think so?
NodeJS and team have been using callbacks from ages presumably from other sources as well. We made use of the most commonky available programming functions
or methods
to more or less avoid the try catch
block. One other part to remember is the try - catch
block makes use of the underlying event system. Depending on the need, one can now use either of them.
Now, let us say we like to implement callbacks in language like Csharp
. Would you think it is possible?
Yes, one could make use of Action
( no return type in args ) or the Func
( last arg is the return type). Refer to this gist or star it here