【问题标题】:Promise function not resolving (javascript/Wit.ai)Promise 函数无法解析 (javascript/Wit.ai)
【发布时间】: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


【解决方案1】:

您的 buildSenario 应该看起来像这样,但如果您以当前的方式使用它就可以了。您可以忽略它,因为它是一条警告消息。

buildScenario({{sessionId, context, text, entities}}) {});

您的某些回调或 Promise 似乎没有在 10 秒内得到解决。

我只在 wit.ai 和 fb bot integartion 上工作过,在 messenger bot 节点应该在接收短信时发送 200 状态。看看这段代码。

wit.ai example for fb messenger integration

【讨论】:

  • 为什么你的参数周围有两组花括号 {}?
  • 哦!抱歉,这是一个错误...忽略它们 buildScenario({sessionId, context, text,entities}) {});
【解决方案2】:

原来我的包依赖项将我的 node-wit API 版本限制为 3.3.2,并且不允许它在以后更新(API 变得基于 Promise,而不是在 v4.0.0 中使用回调)。一旦我编辑了我的 package.json 文件以启用最新版本的 node-wit,我就让它工作了。

【讨论】:

    猜你喜欢
    • 2020-06-11
    • 2015-08-15
    • 2023-01-18
    • 2017-05-22
    • 1970-01-01
    • 2021-09-03
    • 1970-01-01
    • 2019-09-12
    • 2020-06-27
    相关资源
    最近更新 更多