Wait for DB Response Without Callbacks

Shubham
Webtips
Published in
3 min readJun 29, 2019

I am sure it has happened to almost all Javascript developers when they got confused about how promises and callbacks in Javascript work. From my past experience, I can say that a lot of JS developers make the mistake where we made a Database call and try to print the response in the next line. But real frustration builds up when we see in our console is undefined.

Cause and Solution

Let’s talk about the cause and solution. Well, of course, one possible solution could be to use callback but in the era of async/await using callbacks doesn’t seem right. Plus it can make your code really messy in no time. So how do we wait for a Database call to finish and then proceed with the rest of the code?

We can do this with the combination of Promise and async/await. Let's look at the code:

Now to mimic a DB call request I am using setTimeout function that will wait for some time until the response is available and then return it.

What do you think will be printed in console.log? If you guessed undefined you are absolutely right!

And the reason is Database call is an asynchronous request, so its response will not be available immediately. Instead, you have to wait for its response to be available. You can do that either by passing a callback function that should be invoked once the response is available or you can do it using async/await.

async/await in Action

Let’s restructure the code using async/await and see how it solves the undefined issue:

If you run the above code, you will see how we are no longer getting undefined, also our console.log function is only called after response comes back from DB, which in our case is after setTimeout function runs.

So let’s try to understand what we did here.

First of all now in our DBCall function, instead of returning the result, we are returning a promise by generating a new one inside DBCall function. And then we use async/await for the promise returned by DBCall function to get resolved before running the console.log function in the next line. (You can also reject by a promise and catch it using try-catch block and that will work just fine).

So you can see how by returning a promise and using async/await we can solve this issue without even using callbacks.

Hopefully, you liked this. The entire code is available to try and play in the code pen. Link mentioned below:

--

--

Shubham
Webtips
Writer for

Full Stack Eng | Javascript | Node | MongoDB. Love to share about Javascript ➡️ caveats | mistakes | good coding practice | Instagram Youtube -@indiandevjourney