如何在节点 js 中使用 Promise 以在带有 actions-on-google 库的 dialogflow fulfillment 中进行 mongodb 查询?

How to use Promise in node js for mongodb query in dialogflow fulfillment with actions-on-google library?

在我的 dialogflow fulfillment 中,我想查询一个 mongodb 数据库并根据结果 return 一个答案。由于我使用 actions-on-google 数据库,我必须使用 promises 进行异步调用。 我如何为 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)
});

如果您不传递回调函数,Node mongodb 包将 return 来自大多数(也许是全部?)基于回调的 API 的 Promise。例如,您可以调用 db.collection('paths').then(function (collection) { … })。然后你可以像下面这样链接承诺:

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);
  });

您还可以使用 new Promise((resolve, reject) => …) 构造函数来包装任何基于 Promise API 的回调。 MDN 上的 Promise 文档有一个很好的例子 here.