Skip to main content

Awaiting on async method call in JS

· 2 min read
Ragavendra Nagraj

Have you ever been in a situation where you have spent hours together trying to debug as to why that database query is not awaited even after using the await for an async method.

Lately, I ran into an issue where the database call was passed and the method run finished with the undefined in the database response even after using await. After spending hours trying to fix it, one article took me back top using a Promise in javascript. Unfortunately this did not end the story as little was known to me that the two methods resolve and reject passed as params to the lambda call can be utilized to fetch the return response from that call like below.

export function getDataFromDb() {
var response = new Promise((resolve, reject) => {
....
// lines to fetch data from db
....

if(error) {
reject(error);
}

resolve(dbData);
})

return response
}

....
....
// make async call
var result = await getDataFromDb();
....

The resolve() call actually returns the response from the database call or similar.

Promise actually helps in awaiting the response from this or similar async calls and it also gives the benefit of reject the response, if an error was found.