Log time taken to execute aync await function - javascript

How can I find how much time this function takes to execute?
export async function queryElasticSearch(userQuery, index) {
if (_.isEmpty(userQuery)) {
throw new Error('User query is empty or null');
}
try {
const elasticSearchRequestBody = getElasticSearchRequestBody(index, userQuery);
return await elasticSearchClient.search(elasticSearchRequestBody);
} catch (err) {
throw err;
}
}

Something like this:
export async function queryElasticSearch(userQuery, index) {
const start = Date.now()
try {
if (_.isEmpty(userQuery)) throw new Error('User query is empty or null');
const elasticSearchRequestBody = getElasticSearchRequestBody(index, userQuery);
return await elasticSearchClient.search(elasticSearchRequestBody);
} finally {
console.log(Date.now() - start)
}
}
Or alternatively, you can use performance.now() if you want precision in microseconds...
Edit: added finally per Bergi suggestion.

you can also implement this with console.time ie
export async function queryElasticSearch(userQuery, index) {
console.time('time');
try {
if (_.isEmpty(userQuery)) throw new Error('User query is empty or null');
const elasticSearchRequestBody = getElasticSearchRequestBody(index, userQuery);
return await elasticSearchClient.search(elasticSearchRequestBody);
} finally {
console.timeEnd('time')
}
}

Related

Class in Nodejs does not return expected value when using parameter

I have a class on my node server, each function of it returns something from another api, the first function that I will show does not use a parameter, it returns the items correctly, the second that uses the Make parameter, does not return anything, and does not point out error
function getInventory:
(this function works normally)
async getInventory() {
try {
let res = await axios.get(URL);
let data = res.data;
return data;
} catch (err) {
return err;
}
}
function getMakesNew(make): (this function works without errors but does not return anything)
async getMakesNew(make) {
try {
let res = await axios.get(URL);
let data = res.data;
let count = 0;
while (data != make) {
if (data[count].ID === make) {
return data[count].Name;
} else {
count++;
}
}
} catch (err) {
return err;
}
}
Calling the two functions on the routes:
// GetInventory
routes.get('/getInventory', async (req, res) => {
return res.json(await Vehicle.getInventory());
});
// getMakesNew
routes.get('/getMakesNew/:make', async (req, res) => {
let { make } = req.params;
return res.json(await Vehicle.getMakesNew(make));
});
function getMakesNew returns:
{}
return keyword is missing from your second function

Function return null, await result not applied

I am using the below function within post method. The async-await is used but in transferAmount totalBalance is not updated when I call the function inside the post route. The return from the function is not proper. I need guidance so that it returns the object with updated values.
async function transferAmount(fromAccountId, toAccountId, amount) {
const session = await mongoose.startSession();
const options= {session, new:true}
let sourceAccount, destinationAccount;
const BASICSAVNGS_MAX_BALANCE = 1500;
const result = {
newSrcBalance: 0,
totalDestBalance:0,
transferedAt:moment.now()
}
try {
session.startTransaction();
const source= await Account.findByIdAndUpdate(
{_id:sourceAccount._id},
{$inc:{balance:-amount}},
options
);
if(source.balance <0) {
// Source account should have the required amount for the transaction to succeed
const errorMessage='Insufficient Balance with Sender:';
throw new ErrorHandler(404,errorMessage);
}
const destination = await Account.findByIdAndUpdate(
{_id:destinationAccount._id},
{$inc:{balance:amount}},
options
);
// The balance in ‘BasicSavings’ account type should never exceed Rs. 50,000
if((destination.accountType.name === 'BasicSavings') && (destination.balance > BASICSAVNGS_MAX_BALANCE)) {
const errorMessage=`Recepient's maximum account limit reached`;
throw new ErrorHandler(404,errorMessage);
}
await session.commitTransaction();
result.transferedAt= moment.now() //*UPDATE THE TRANSFER TIMESTAMP
result.newSrcBalance = source.balance; //*UPDATE THE SOURCE BALANCE
session.endSession();
// finding total balance in destination account
await User.findById(destination.user.id, async function(err,user) {
if(err) {
const errorMessage=`Recepient not found!`;
console.log(err);
throw new ErrorHandler(404,errorMessage);
} else {
if(user.accounts) {
await Account.find({
'_id' :{$in:user.accounts}
}, function(err,userAccounts) {
totalDestBalance = userAccounts.reduce( (accumulator,obj) => accumulator+obj.balance,0);
result.totalDestBalance = totalDestBalance; //*UPDATE THE TOTAL BALANCE
console.log(result);
return result;
});
}
}
});
}
catch (error) {
// Abort transaction and undo any changes
await session.abortTransaction();
session.endSession();
throw new ErrorHandler(404,error);
} finally {
if(session) {
session.endSession();
}
}
}
module.exports = transferAmount;
Result of above function is
{
newSrcBalance: 940,
totalDestBalance: 1060,
transferedAt: 1594982541900
}
But inside the post request below it is {}
const result = await transferAmount(fromAccountId, toAccountId, amount);
You are not returning something inside the function.
User.findById - this receives a callback for returning something.
You can convert it as async/await syntax or have to resolve the result with promise.
Like below:
try {
const user = await User.findById(destination.user.id);
if (user.accounts) {
const userAccounts = await Account.find({ _id: { $in: user.accounts } });
totalDestBalance = userAccounts.reduce((accumulator, obj) => accumulator + obj.balance, 0);
result.totalDestBalance = totalDestBalance; //*UPDATE THE TOTAL BALANCE
console.log(result);
return result;
}
} catch (err) {
const errorMessage = `Recepient not found!`;
console.log(err);
throw new ErrorHandler(404, errorMessage);
}
Or:
return new Promise((resolve, reject) => {
User.findById(destination.user.id, async function(err, user) {
if (err) {
const errorMessage = `Recepient not found!`;
console.log(err);
reject(err);
} else {
if (user.accounts) {
await Account.find(
{
_id: { $in: user.accounts },
},
function(err, userAccounts) {
totalDestBalance = userAccounts.reduce((accumulator, obj) => accumulator + obj.balance, 0);
result.totalDestBalance = totalDestBalance; //*UPDATE THE TOTAL BALANCE
console.log(result);
resolve(result);
}
);
}
}
});
});
I may be wrong but i cannot see a return statement in you transferAmount function.

Promise returning undefined result to callback

I'm having issues with getting the result of a callback function. Below is the async function that I'm calling
const utils = {
sendQuery: async function(query){
// Receives a query and returns raw results
// Query is using default database specified by pool
// Returns a Promise
let conn;
try {
conn = await pool.getConnection();
let queryString = query;
let rows = await conn.query(queryString);
let results = (this.formatResults(rows));
console.log(results);
return results;
} catch(err) {
throw new Error(err);
} finally {
if (conn) return conn.end();
}
}
module.exports = {
'utils': utils
}
the console log above returns the expected result.
and below is the function that calls the above
const db = require('../private/db');
db.utils.sendQuery(queryString).then(function(result){
console.log(result);
}).catch(err=>{
throw res.render('error', {'error': err.stack});
})
the console log above returns undefined and I have no idea why.
The real problem here is this part if (conn) return conn.end();.
Whenever you are using finally, it will override any previous return, break, continue or throw that happens either in the stated try or catch blocks.
To fix your issue you should do like so:
const utils = {
sendQuery: async function(query){
// Receives a query and returns raw results
// Query is using default database specified by pool
// Returns a Promise
let conn;
try {
conn = await pool.getConnection();
let queryString = query;
let rows = await conn.query(queryString);
let results = (this.formatResults(rows));
console.log(results);
return results;
} catch(err) {
throw new Error(err);
} finally {
if (conn) conn.end();
}
}
module.exports = {
'utils': utils
}
Hope it works
In my opinion, just return results instead of resolve(results). Your function is already async and no promise object is created here.
And just throw err instead of reject(err);
And since you return in your try, you don't need your finally statement.
You need to simply return the result instead of calling resolve
const utils = {
sendQuery: async function(query){
// Receives a query and returns raw results
// Query is using default database specified by pool
// Returns a Promise
let conn;
try {
conn = await pool.getConnection();
let queryString = query;
let rows = await conn.query(queryString);
let results = (this.formatResults(rows));
console.log(results);
return results;
} catch(err) {
throw new Error(err)
} finally {
if (conn) return conn.end();
}
}
module.exports = {
'utils': utils
}
you could simply return or i suppose this is what you were trying to do
sendQuery: (query) => {
let promise = new Promise(async (resolve, reject) => {
let conn;
try {
conn = await pool.getConnection();
let queryString = query;
let rows = await conn.query(queryString);
let results = (this.formatResults(rows));
console.log(results);
resolve(results);
} catch (err) {
reject(err);
} finally {
if (conn) {
conn.end();
}
}
})
return promise;
}

Try/Catch/Finnaly with ESLint Expected to return a value at the end of async arrow function

I have this ESLint error in my code:
function(productId: any): Promise
Expected to return a value at the end of async arrow function
export const getGooglePlayPayment = async (productId) => {
await InAppBilling.close();
try {
await InAppBilling.open();
if (!await InAppBilling.isSubscribed(productId)) {
const details = await InAppBilling.subscribe(productId);
console.log('You purchased: ', details);
return details.purchaseState === PAYMENT_STATE.PurchasedSuccessfully;
}
} catch (err) {
console.log(err);
return false;
} finally {
await InAppBilling.consumePurchase(productId);
await InAppBilling.close();
}
};
Someone can help me to fix this issue without having to disabled the ESLing rule :)
thanks
The rule here is consistent-return.
You are not returning anything if the if statement in the try block is not fulfilled. You should return something if the isSubscribed call is truthy:
export const getGooglePlayPayment = async (productId) => {
await InAppBilling.close();
try {
await InAppBilling.open();
if (!await InAppBilling.isSubscribed(productId)) {
const details = await InAppBilling.subscribe(productId);
console.log('You purchased: ', details);
return details.purchaseState === PAYMENT_STATE.PurchasedSuccessfully;
}
return 'Already subscribed';
} catch (err) {
console.log(err);
return false;
} finally {
await InAppBilling.consumePurchase(productId);
await InAppBilling.close();
}
};
(Of course, replace Already subscribed with whatever would make most sense there. If you just want to indicate that the transaction succeeded, perhaps return true. The important thing is to distinguish it from the return false in the catch.)

How can I wait to electron while loading html

I have an electron app which loads an HTML file on opening.
When I tried to wait for an element with waitUntil method from the opening page, Spectron tries to find that while page loading and it crashes my app and app staying at the blank page. How can I wait for loading of this HTML?
My application launch code is below :
async start() {
try {
await this.spectron.start();
await this.focusOnWindow(0);
return this._checkWindowReady();
} catch (err) {
throw err;
}
}
beforeEach(async function (){
app = new SpectronApplication();
common = new CommonActions();
await app.start();
})
I found a solution like below code :
Firstly when I call app.start() ,
start() function calls _checkWindowReady()
_checkWindowReady calls waitFor()
And finally waitFor calls _callClientAPI() and it looks for specific function and element.
async start() {
try {
await this.spectron.start();
await this.focusOnWindow(0);
return this._checkWindowReady();
} catch (err) {
throw err;
}
}
_checkWindowReady() {
return this.waitFor(this.spectron.client.getHTML, '[id="myApp.main.body"]');
}
waitFor(func, args) {
return this._callClientAPI(func, args);
}
_callClientAPI(func, args) {
let trial = 1;
return new Promise(async(res, rej) => {
while (true) {
if (trial > this._pollTrials) {
rej(`Could not retrieve the element in ${this._pollTrials * this._pollTimeout} seconds.`);
break;
}
let result;
try {
result = await func.call(this.client, args, false);
} catch (e) { }
if (result && result !== '') {
res(result);
break;
}
await this.wait();
trial++;
}
});
}

Categories

Resources