Feature Applied with Promises

I am working on a promise-based project in Node.js using bluebird and the other in native ES6 promises. In both cases, I have a chain where I query the database in the following form:

some_function(/*...*/) .then(function () { return query("SELECT `whatever` FROM `wherever` ") }) .then(/*...*/) 

Note that query obviously returns the promise resolved to the query result. This is repeated in several chains, and I'm looking for a way to clear the unused shell of a function.

I would naturally use Function.prototype.apply() , but in this case, when I try:

 .then(query.apply(this, ["SELECT * FROM ... "])) .then(function(rows){ /*...*/ }) 

The next function in the chain gets rows as undefined .

Thanks. Your help is appreciated.

+5
source share
2 answers

You must pass a link to the .then() function so that your options are as follows:

  • Use the built-in anonymous function like you.
  • Create your own utility function that returns another function (see example below)
  • Use .bind() to create another function.

Built-in Anonymous

 some_function(/*...*/).then(function () { return query.apply("SELECT `whatever` FROM `wherever` ") }).then(/*...*/) 

Your own shell of functions

 function queryWrap(q) { return function() { return query.apply(q); } } some_function(/*...*/) .then(queryWrap("SELECT `whatever` FROM `wherever` ")) .then(/*...*/) 

This shell can be useful if you can use it in several places. Probably not worth it for a single call.

Use .bind ()

 some_function(/*...*/) .then(query.apply.bind(query, "SELECT `whatever` FROM `wherever` ")) .then(/*...*/) 
+4
source

In es6, arrow functions solve this in the best way:

 .then(() => query.apply("SELECT `whatever` FROM `wherever` ")) .then(rows => { /*...*/ }) 
+3
source

All Articles