javascript - Function apply with Promises -
i'm working on promise-based project in node.js using bluebird, , in native promises es6. in both, have chain query database in following form:
some_function(/*...*/) .then(function () { return query("select `whatever` `wherever` ") }) .then(/*...*/)
note query
returns promise resolved query result. repeats in several chains, , i'm looking way clean unused function wrapper.
i'd naturally use function.prototype.apply()
, in case, when try:
.then(query.apply(this, ["select * ... "])) .then(function(rows){ /*...*/ })
the next function in chain gets rows
undefined
.
thanks ahead. appreciated.
you have pass function reference .then()
choices follows:
- use inline anonymous function are.
- create own utility function returns function (see example below)
- use
.bind()
create function.
the inline anonymous
some_function(/*...*/).then(function () { return query.apply("select `whatever` `wherever` ") }).then(/*...*/)
your own function wrapper
function querywrap(q) { return function() { return query.apply(q); } } some_function(/*...*/) .then(querywrap("select `whatever` `wherever` ")) .then(/*...*/)
this wrapper useful if use in multiple places. not worth 1 invocation.
use .bind()
some_function(/*...*/) .then(query.apply.bind(query, "select `whatever` `wherever` ")) .then(/*...*/)
Comments
Post a Comment