Question

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);
  }
Was it helpful?

Solution

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}))
 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top