我正在尝试更新我的 messenger/wit.ai 聊天机器人中的函数,从使用回调到 Promise。
这种原始格式执行得很好:
['buildScenario'](sessionId, context, cb) {
var trendChoice = scenarioCombos['trends']
var disruptionChoice = scenarioCombos['disruptions']
context.trend = trendChoice[Math.floor(Math.random() * trendChoice.length)]
context.disruption = disruptionChoice[Math.floor(Math.random() * disruptionChoice.length)]
cb(context)
},
但是当我如下更新到 Promises 时,它并没有通过:
['buildScenario']({sessionId, context, entities}) {
return new Promise(function(resolve, reject) {
var trendChoice = scenarioCombos['trends']
var disruptionChoice = scenarioCombos['disruptions']
context.trend = trendChoice[Math.floor(Math.random() * trendChoice.length)]
context.disruption = disruptionChoice[Math.floor(Math.random() * disruptionChoice.length)]
return resolve(context)
})
},
我尝试通过在整个函数中添加控制台日志来进行调试,如下所示:
当函数被触发时,它中途停止并且无法解决承诺:
当我在函数中尝试 console.log(context) 时,我得到“未定义”。
我错过了什么?
编辑:当我删除函数参数周围的大括号时,如下所示:
['buildScenario'](sessionId, context, entities) {
console.log('BS POINT 1')
return new Promise(function(resolve, reject) {
console.log('BS POINT 2')
var trendChoice = scenarioCombos['trends']
console.log(trendChoice)
console.log('BS POINT 3')
var disruptionChoice = scenarioCombos['disruptions']
console.log(disruptionChoice)
console.log('BS POINT 4')
console.log(context)
context.trend = trendChoice[Math.floor(Math.random() * trendChoice.length)]
console.log(context)
console.log('BS POINT 5')
context.disruption = disruptionChoice[Math.floor(Math.random() * disruptionChoice.length)]
console.log(context)
console.log('BS POINT 6')
return resolve(context)
})
},
我可以记录我的上下文,但仍然无法解决 Promise: