【发布时间】:2016-09-09 06:21:45
【问题描述】:
我正在尝试更新我的 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)
})
},
我尝试通过在整个函数中添加控制台日志来进行调试,如下所示:
函数触发时,中途停止,无法解析promise:
当我在函数中尝试 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:
【问题讨论】:
-
你可以试试resolve(context),没有return语句。
-
无变化,仍达到 POINT 4 并超时,然后发送“无回调”警告。
-
你添加了 Promise polyfill 了吗?如果您计划在 Internet Exploder 上运行它,则需要这样做。
-
我没有,但我现在有,我仍然遇到同样的问题(假设我正确安装了 polyfill)。
标签: javascript wit.ai