繁体   English   中英

处理异步数据库调用

[英]Handle async DB calls

我用node.js做了几个项目,我知道了异步行为,通常应该使用回调函数,等等。但是有一件事情困扰着我。

我正在开发Alexa技能,并且具有处理用户意图的功能:

 'MyFunction': function() { var toSay = ""; // Holds info what Alexa says // Lot of checks and calculations what needs to be said by Alexa (nothing special) if(xyz) { toSay = "XYZ"; }else if(abc) { toSay = "ABC"; }else{ toSay = "Something"; } // Here is the "tricky" party if(someSpecialEvent) { toSay += " "+askDatabaseForInput(); // Add some information from database to string } this.emit(':ask', toSay, this.t('REPROMT_SPEECH')); // Gives the Info to Alexa (code execution stops here) } 

如代码中所提到的,通常有一些代码可以用来找出Alexa的输出。 仅在罕见事件“ someSpecialEvent”上,我需要查询数据库并将信息添加到字符串“ toSay”。

查询数据库如下所示:

 function askDatabaseForInput() { // The function to query the DB var params = { TableName: "MyTable", OtherValues: "..." }; // Do the Query docClient.query(params, function(err, data) { // Of course here are some checks if everything worked, etc. var item = data.Items[0]; return item; // Item SHOULD be returned }); return infoFromDocClient; // Which is, of course not possible } 

现在我知道,在第一个函数“'MyFunction'”中,我可以将变量“ toSay”传递给数据库函数,然后传递给数据库查询,如果一切正常,我可以执行“ this.emit()”。在数据库查询功能中。 但是对我来说,这看起来很脏而且没有太多可重用性。

因此,有没有一种方法可以使用“ askDatabaseForInput()”返回数据库信息并将其添加到字符串中? 这意味着使异步调用同步。

进行同步调用不会影响用户体验,因为代码无论如何都不会做其他任何事情,它只会创建String并(可能)正在等待DB输入。

谢谢你的帮助。

因此,您可以做两件事:

就像发表评论的人说的那样,您可以使用回调:

function askDatabaseForInput(callback) {
  var params = {
    TableName: "MyTable",
    OtherValues: "..."
  };

  docClient.query(params, function(err, data) {
    if (err) {
      callback(err, null)
    } else {
      var item = data.Items[0]; 
      callback(null, item);
    }
  });
}

或者您可以使用诺言:

function askDatabaseForInput() {
  var params = {
    TableName: "MyTable",
    OtherValues: "..."
  };
  return new Promise(function (resolve, reject) {
    docClient.query(params, function(err, data) {
      if (err) {
        reject(err)
      } else {
        var item = data.Items[0]; 
        resolve(item);
      }
    });
  });
}

然后,您可以在调用askDatabaseForInput的地方放置一个函数,也可以执行askDatabaseForInput.then(....)

在函数或toSay .then您将将从数据库中检索到的内容添加到变量toSay

希望这可以帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM