How to remove template code when using q in node.js

I am currently using q with Node.js. All my models use promises from q. Later I realized that I wrote a lot of templates, such as

count: function(){
  var deferred = Q.defer()
  User.count(function(err,count){
    if(err)
      deferred.reject(err)
    else
      deferred.resolve(count)
  })
  return deferred.promise;
},
findAll: function(){
  var deferred = Q.defer()
  User.find({}, function(err,users){
    if(err)
      deferred.reject(err)
    else
      deferred.resolve(users)
  })
  return deferred.promise;
}

Is there any way to remove this boilerplate code?

+4
source share
2 answers

Is there any way to remove this boilerplate code?

Yes, Q has dedicated helper functions for interacting with node callbacks .

You can simplify your code to

count: function(){
  return Q.nfcall(User.count);
},
findAll: function(){
  return Q.nfcall(User.find, {});
}

If these methods rely on their value this, you can use Q.ninvoke(User, "count")and Q.ninvoke(User, "find", {}).

, / Q:

count: Q.nfbind(User.count),
findAll: Q.nfbind(User.find, {})

this:

count: Q.nbind(User.count, User),
findAll: Q.nbind(User.find, User, {})

, , count findAll .

+4

. Q , , Q ( OP), . Bergi. lib, , ; , . .


, Node - promises ( ), :

count: function() {
  return makePromise(User.count)
}

makePromise :

function makePromise(f) {
  var deferred = Q.defer()
  var args = Array.prototype.slice.call(arguments)
  args[0] = function(err) {
    if(err)
      deferred.reject(err)
    else
      deferred.resolve(Array.prototype.slice.call(arguments, 1))
  }
  f.apply(null, args)
  return deferred.promise
}

( ;, ASI )

, , , , err, , err. Node, err .

, - : promisify:-) , , .

thisArg :

function makePromise(obj, f) {
  var deferred = Q.defer()
  var args, func, thisArg;
  if (typeof obj === "function") {
    thisArg = null
    func = obj
    args = Array.prototype.slice.call(arguments)
  } else {
    thisArg = obj
    func = f
    args = Array.prototype.slice.call(arguments, 1)
  }
  args[0] = function(err) {
    if(err)
      deferred.reject(err)
    else
      deferred.resolve(Array.prototype.slice.call(arguments, 1))
  }
  func.apply(thisArg, args)
  return deferred.promise
}

, User.count this= User:

count: function() {
  return makePromise(User, User.count)
}
+2

Source: https://habr.com/ru/post/1613305/


All Articles