0

I have an instance of mysql connection named db. db has a method named query to execute sql statement

example

db.query('SELECT * FROM user',[], callback)

To avoid repeating db.query I would like to do something like

const sqlCmd=db.query
sqlCmd('SELECT * FROM user',[], callback)

thanks in advance

3 Answers 3

1

You have to bind the call to the db object:

const sqlCmd=db.query.bind(db)
Sign up to request clarification or add additional context in comments.

Comments

0

what you are trying to do here is called abstraction. Meaning you are adding a layer over the db class. So the simplest solution would be to create a module, add a method called query.

// let db = 'your sql db instance' 

 module.export.sqlCmd = db.query;

import this like

let sqlCmd = require('path to the above code')

Comments

0

You can use the new Function() syntax, it's rarely used though:

const queryDB = new Function(`db.query('SELECT * FROM user',[], callback)`)
//then you can call it as:
queryDB()

you can also pass pass arguments as new Function(['argA', 'argB'], "function body")

Remember, [[Environment]] is set to reference not the current Lexical Environment, but the global one.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.