我正在处理使用hapi并执行node-rules规则的服务器。
我有一个回调,由R.execute方法从node-rules调用。作为执行Promise的结果,我需要从exec方法返回一个callback。
码
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)
}
}我从源代码中注意到,R.execute不返回任何我可以使用的内容。我注意到在execute中递归地调用这个功能在这里,但是在没有回调的情况下不会终止。
如何将其转换为返回承诺的函数?
发布于 2017-07-31 08:11:39
在浏览其他问题的一些答案时,我想起了$.deferred和Q.defer API,找到了一个类似于它们的解决方案:
deferred并解决承诺promise创建的deferred我不想要一个自定义承诺实现或猴子补丁的
PromiseAPI。如果后者不是一个问题,那么在npm上有几个模块可以做到这一点,并且可以实现多填充Promise.defer。
defer函数是从这里开始
代码现在看起来如下:
/* eslint-disable promise/param-names */
function defer () {
let resolve, reject
const promise = new Promise(function (...args) {
resolve = args[0]
reject = args[1]
})
return {resolve, reject, promise}
}
/* eslint-enable promise/param-names */
const makeCallback = deferred => 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'
)
}
deferred.resolve(descision)
}
function exec (input) {
const {medicineType, facts: data} = input
const R = new RuleEngine()
R.register(rules)
if (lenderType !== 'generic') {
const facts = {
data
}
const deferred = defer()
const callback = makeCallback(deferred)
R.execute(facts, callback)
return deferred.promise
}
}发布于 2017-07-31 07:08:44
不确定我是否理解正确,但这样的事情可能会发生
function exec(input) {
const { medicineType, facts: data } = input
const R = new RuleEngine()
R.register(rules)
return new Promise(function(resolve, reject) {
if (medicineType !== 'generic') {
const facts = {
data
}
R.execute(facts, function(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'
)
}
resolve('<return here whatever you want>')
// or
// reject('<return some error>')
});
} else {
reject('<return some error>')
}
})
}https://stackoverflow.com/questions/45409130
复制相似问题