[英]How to use Promise in node js for mongodb query in dialogflow fulfillment with actions-on-google library?
In my dialogflow fulfillment, I want to query a mongodb database and based on the result return an answer. 在我的对话框流实现中,我想查询一个mongodb数据库,并根据结果返回答案。 Since I use the actions-on-google database, I must use promises for async calls.
由于我使用的是Google Actions数据库,因此必须对异步调用使用Promise。 How can I do that for a mongodb query?
如何对mongodb查询执行此操作?
const express = require("express"); const bodyParser = require("body-parser"); const {dialogflow} = require('actions-on-google'); const app = dialogflow() var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/" app.intent('Mongodb', (conv) =>{ MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("mydb"); var query = { address: /^S/ }; var path; db.collection('paths', function(err, collection) { collection.find({}).toArray(function(err, results) { path = results; console.log(results); }); }); }); conv.ask(path) });
The Node mongodb package will return a Promise from most (maybe all?) of its callback-based APIs if you don't pass a callback function. 如果您不传递回调函数,Node mongodb程序包将从其大多数基于回调的API中返回一个Promise(可能是全部?)。 For example, you can call
db.collection('paths').then(function (collection) { … })
. 例如,您可以调用
db.collection('paths').then(function (collection) { … })
。 You can then chain the promises like the following: 然后,您可以像下面这样链接promise:
return MongoClient.connect(url)
.then(function (client) {
return client.db('mydb');
}).then(function (db) {
return db.collection('paths');
}).then(function (collection) {
return collection.find({}).toArray();
}).then(function (path) {
conv.ask(path);
});
You can also use the new Promise((resolve, reject) => …)
constructor to wrap anything that is callback based in a Promise API. 您还可以使用
new Promise((resolve, reject) => …)
构造函数包装Promise API中基于回调的任何内容。 The Promise documentation on MDN has a good example here . 关于MDN的Promise文档在这里有一个很好的例子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.