如何从函数正确获取返回值并分配给变量

时间:2019-03-23 20:50:40

标签: node.js azure-bot-service

我正在尝试编写一个程序来尝试Azure bot服务以及node.js的新功能。添加了一些功能进行测试,但是为了使动态特性能够处理多个用户,我想在数据库中查找会话ID并初始化学生ID。

但是我变得不确定了。

我尝试了其他页面中定义的方法,在某个地方我做错了,最终出现错误和错误的实现。由于我可以轻松地进行归纳,下面的任何更正将有助于进一步发展,并有助于更好地理解用法。另外,不确定如何处理多个呼叫。请不要介意。

//Function 1 to execute queries on database and return the output
function queryDatabase(query, callback=null, errcallback=null) {
  connect(function(connection) {

    const request = new Request(query, function(err, rowCount) {
      if (err) {
        if(errcallback) { errcallback(err); }
        console.log(`ERROR in QUERY: ${err}`);
      } else {
        console.log(rowCount + ' rows');
      }
      connection.close();
    });

    request.on('row', function(columns) {
      columns.forEach(function(column) {
        if (column.value === null) {
          console.log('NULL');
        } else {
          if(callback) {
            callback(column.value);
          }
        }
      });
    });
    connection.execSql(request);
  });
}

//Function 2 to fetch the ID based on passed sessionID.
function lookup_session_suid(sessionID) {
   var slackId = sessionID;
   var studentid;
   queryDatabase(`select suid from studentprofile where SlackUserID = '${slackId}'`, function(ID) {
    studentid=ID;
    console.log("The value of suid in the look up before end --->", studentid); // printing correct value , line #36
  });
  console.log("The value of ID in the look up session --->", studentid);  //getting undefined , line #38
  return studentid;
}


//Main method that triggers and calls the Function2 
bot.dialog('GreetingDialog',
    (session) => {
      var slackId=session.message.address.user.id;
      var ID = lookup_session_suid(slackId);
      console.log("Debug: before Greeting: Your id is -----> %s", ID);  //getting undefined, line #48

       queryDatabase(`select TOP 1 Fact from FunFacts order by newid()`, function(value) {
        console.log("Debug: after Greeting: Your id is -----> %s", ID); //getting undefined, line #51
        session.endDialog();
       });
    }
    ).triggerAction({
    matches: 'Greeting'
});


bot.dialog ( //follows other dialogs);


//observation: The order of statements in the console log are in below line order.

38
48
36
51

我希望

var ID = lookup_session_suid(slackId);

使用正确的值初始化,并且函数也正确返回该值。

0 个答案:

没有答案