【问题标题】:How to pass variable from one function to another function in Node.js?如何将变量从一个函数传递到 Node.js 中的另一个函数?
【发布时间】:2017-08-10 20:38:37
【问题描述】:

我想将topic_to_learn 变量传递给第二个函数,并在第二个函数中用于其他用途。

    function (session, args, next) {
        var topic_to_learn = builder.EntityRecognizer.findEntity(args.entities, 'topic_to_learn');
        builder.Prompts.text(session, 'Sure, can you please also tell me about your goals or anything you want to achieve after learning about this topic?');
    },
    function (session, results, next) {
        var learning_goals = results.response;
        session.send('Got it, let me think...', session.message.text);
        session.send('Voila! These are the articles related to ' + topic_to_learn, session.message.text);
    },

【问题讨论】:

  • 请提供完整代码或至少一个minimal reproducible example。这两个中间有逗号的函数表达式单独存在时是语法错误。他们在互相打电话吗?完全不清楚它们是如何使用的。
  • 非常感谢,您的所有回答都启发了我,我找到了方法,非常感谢!!

标签: javascript node.js bots azure-language-understanding


【解决方案1】:

您可能想要使用一个上述范围的变量,这两个函数都可以使用。

   var topic_to_learn;

    function (session, args, next) {
        topic_to_learn = builder.EntityRecognizer.findEntity(args.entities, 'topic_to_learn');
        builder.Prompts.text(session, 'Sure, can you please also tell me about your goals or anything you want to achieve after learning about this topic?');
    };

    function (session, results, next) {
        var learning_goals = results.response;
        session.send('Got it, let me think...', session.message.text);
        session.send('Voila! These are the articles related to ' + topic_to_learn, session.message.text);
    },

【讨论】:

  • 非常感谢...我也试过了,但是失败了,我好像不能这样写,因为这两个函数似乎存储在另一个函数中..
  • .matches('get_learning_plan', [ function (session, args, next) { ...
  • 最好的方法是为所有 3 个函数创建一个模块,并在后续函数中连续需要它们。这样您就可以像访问对象属性一样访问函数内部的变量 (func1.topic_to_learn)
  • 嘿,伙计,我正在使用另一个库,这就是为什么我的代码看起来有点奇怪,但你的回答确实启发了我,我刚刚找到了另一种解决方法,非常感谢!
【解决方案2】:
.matches('get_learning_plan', [

        function (session, args, next) {
            var topic_to_learn = builder.EntityRecognizer.findEntity(args.entities, 'topic_to_learn');
            builder.Prompts.text(session, 'Sure, can you please also tell me about your goals or anything you want to achieve after learning about this topic?');
        },
        function (session, results, next) {
            var learning_goals = results.response;
            session.send('Got it, let me think...', session.message.text);
            session.send('Voila! These are the articles related to ' + topic_to_learn, session.message.text);
        },

【讨论】:

  • 这是答案吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-12
  • 2021-04-23
  • 1970-01-01
相关资源
最近更新 更多