I am working on server that uses hapi
and executes rules from node-rules
.
I have a callback which is called by the R.execute
method from node-rules
. I need to return a Promise
from the exec
method as the result of executing the callback
.
Code
const callback = data => {
const {matchPath, result} = data
descision.setMatchPath(matchPath)
if (!result) {
descision.addMessage(
'No match could be found in the rules provided, either incorrect or non-matching information was provided'
)
}
}
function exec (input) {
const {medicineType, facts: data} = input
const R = new RuleEngine()
R.register(rules)
if (medicineType !== 'generic') {
const facts = {
data
}
R.execute(facts, callback)
}
}
I noticed from the source code that R.execute
does not return anything that I can use. I notice that in execute
calls this function here recursively but does not terminate without the callback.
How can I convert this to a function that returns a Promise?
While browsing through some of the answers for other questions, I remembered the
$.deferred
andQ.defer
API, I found a solution that resembles them:creates a deferred
passes the deferred to the callback
uses the
deferred
and resolve the promiseand most importantly, return the
promise
that was created by thedeferred
The
defer
function is from hereThe code now looks like: