0

I have a javascript function "data.getOrdersByUsersModifiedDate" which is making a call to another function "database.getDb". The first function gets a "request" parameter object which has parameters defined. However I can't seem to be getting my head around as to how I can pass that parameter from data.getOrdersByUsersModifiedDate TO database.getDb so that I can use it at line

var orders = db.order.find().toArray(function(err, result)

How can I pass my request parameter from the top function "getOrdersByUsersModifiedDate" to lower function "database.getDb" so I can use it as a filter when I get orders

data.getOrdersByUsersModifiedDate = function (request, next) {
            database.getDb(function(err, db) {
                if(err) {
                    next(err);
                } else {
                    var orders = db.order.find().toArray(function(err, result) {
                        if(err) return next(err);
                        next(null, result);
                    });
                }
            });
        };

0

1 Answer 1

1

Use bind.

bind and apply allows a developer to specify the context of the function call (this).

Bind creates a new function with the arguments given to bind (from second parameter), whereas apply calls the function with the new context and the parameters passed as an array (see doc).

This will help you solve scoping hell in callback hell.

The poor man's way to achieve this is using let that=this.

Edit: As pointed by the OP in the comments, arrow functions in ES6 do not bind this ; thus using an arrow function solves the OP issue.

data.getOrdersByUsersModifiedDate = function (request, next) {
  database.getDb(function(err, db) {
    if(err) {
      next(err);
    } else {
      let {arg1, arg2, arg3} = request; // This should work with ES6
      var arg1 = request.arg1; // Otherwise this?
      var orders = db.order.find().toArray(function(err, result) {
        if(err) return next(err);
        next(null, result);
      });
    }
  }.bind(this)); // Scope this to the context of getOrdersByUsersModifiedDate
};

Sign up to request clarification or add additional context in comments.

2 Comments

Exactly what I wanted. Did come across Arrow functions as an alternative too.
Yep, arrow functions uses the outer context. I'm adding this in the answer.

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.