문제

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);
  }
도움이 되었습니까?

해결책

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}))
 }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top