1

For learning purposes, I want to show how promises can help solving time dependencies of database operations in JavaScript.

So, I want to show that:

db.find(14);

actually consumes time behind the scenes.

How could I illustrate this time dependency and a possible solution that a Promises provides?

What I have so far is this:

  // data store operation take time
  function _findByUsername(username) {
    var user = _.findWhere(Users, {username: username});
    if (!user) {
      Promise.reject(new Error("User not found."));
    }
    return Promise.resolve(user);
  }
poseid
  • 6,986
  • 10
  • 48
  • 78

1 Answers1

0

An option might be to use the delay function of Bluebird and add a comment as follows:

findByUsername(username) { 
   /* simulates the behavior of a database operation */
   return Promise.delay(10).thenReturn(_.findWhere(Users, {username: username}))
 }
poseid
  • 6,986
  • 10
  • 48
  • 78
  • Why would you deliberately slow your code down? Is this just for mocking? – Benjamin Gruenbaum Apr 24 '14 at 11:33
  • yes. By adding a delay, one could simulate the influence of time at higher abstraction levels, in worst case, even the influence of time-outs. what do you think? the point here is to leave a database connection out, but understand influence of time while promise paths are evaluated. – poseid Apr 24 '14 at 12:00
  • I think the only correct way to determine the response times is to use a database and profile it. Everything other than profiling isn't very useful. – Benjamin Gruenbaum Apr 24 '14 at 12:01