Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 如何在NodeJS/ExpressJS中向路由器回调返回承诺_Node.js_Mongodb_Api_Express_Bluebird - Fatal编程技术网

Node.js 如何在NodeJS/ExpressJS中向路由器回调返回承诺

Node.js 如何在NodeJS/ExpressJS中向路由器回调返回承诺,node.js,mongodb,api,express,bluebird,Node.js,Mongodb,Api,Express,Bluebird,我不熟悉nodejs/expressjs和mongodb。我正在尝试创建一个API,该API将数据公开给我的移动应用程序,我正在尝试使用Ionic framework构建该应用程序 我有这样的路线设置 router.get('/api/jobs', (req, res) => { JobModel.getAllJobsAsync().then((jobs) => res.json(jobs)); //IS THIS THe CORRECT WAY? }); 我的模型中有一个从M

我不熟悉nodejs/expressjs和mongodb。我正在尝试创建一个API,该API将数据公开给我的移动应用程序,我正在尝试使用Ionic framework构建该应用程序

我有这样的路线设置

router.get('/api/jobs', (req, res) => {
  JobModel.getAllJobsAsync().then((jobs) => res.json(jobs)); //IS THIS THe CORRECT WAY?
});
我的模型中有一个从Mongodb读取数据的函数。我正在使用Bluebird promise库将我的模型函数转换为返回承诺

const JobModel = Promise.promisifyAll(require('../models/Job'));
我在模型中的作用

static getAllJobs(cb) {

    MongoClient.connectAsync(utils.getConnectionString()).then((db) => {

      const jobs = db.collection('jobs');
      jobs.find().toArray((err, jobs) => {

        if(err) {
          return cb(err);
        }

        return cb(null, jobs);
      });
    });
  }
promisifyAll(myModule)将此函数转换为返回承诺

我不确定的是

  • 这是否是从我的模型返回数据到路由回调函数的正确方法
  • 这有效吗
  • 使用promisifyAll很慢?因为它遍历模块中的所有函数,并创建一个后缀为Async的函数副本,该后缀现在返回一个承诺。它实际上什么时候运行?这是一个与node require语句相关的更一般的问题。见下一点
  • 什么时候运行所有require语句?我什么时候启动nodejs服务器?或者当我调用api时

你的基本结构或多或少是正确的,尽管你使用的
promisifyAll
对我来说似乎很尴尬。对我来说,最基本的问题(其实这并不是一个问题——您的代码看起来可以正常工作)是混合和匹配基于承诺和基于回调的异步代码。正如我所说的,这应该仍然有效,但我更愿意尽可能坚持一个

如果您的模型类是您的代码(而不是其他人编写的库),您可以轻松地重写它以直接使用承诺,而不是为回调编写它,然后使用
promisifyAll
包装它

下面是我将如何处理
getAllJobs
方法:

static getAllJobs() {

    // connect to the Mongo server
    return MongoClient.connectAsync(utils.getConnectionString())

        // ...then do something with the collection
        .then((db) => {
            // get the collection of jobs
            const jobs = db.collection('jobs');

            // I'm not that familiar with Mongo - I'm going to assume that
            // the call to `jobs.find().toArray()` is asynchronous and only 
            // available in the "callback flavored" form.

            // returning a new Promise here (in the `then` block) allows you
            // to add the results of the asynchronous call to the chain of
            // `then` handlers. The promise will be resolved (or rejected) 
            // when the results of the `job().find().toArray()` method are 
            // known
            return new Promise((resolve, reject) => {
                jobs.find().toArray((err, jobs) => {
                    if(err) {
                        reject(err);
                    }
                    resolve(jobs);
                });
            });
        });
}
此版本的
getAllJobs
返回一个承诺,您可以将
然后
catch
处理程序链接到该承诺。例如:

JobModel.getAllJobs()

    .then((jobs) => {
        // this is the object passed into the `resolve` call in the callback
        // above. Do something interesting with it, like
        res.json(jobs);
    })

    .catch((err) => {
        // this is the error passed into the call to `reject` above
    });
诚然,这与上面的代码非常相似。唯一的区别是我没有使用promisifyAll,promisifyAll,如果你自己写代码&你想使用promises,那就自己做吧


一个重要的注意事项是:最好包含一个
catch
处理程序。如果您不这样做,您的错误将被吞没并消失,您将疑惑代码为什么不能工作。即使您认为不需要它,也只需编写一个catch处理程序,将其转储到
console.log
。你会很高兴你做到了

看看猫鼬模块。@Yahya我已经研究过了。但是我不想在我的文档上强制使用模式。那怎么办?@Yahya-我确实尝试过使用mongojs。但是这些库并没有像原生mongod那样提供最新的可用特性/功能,所以我尝试使用原生mongod。在阅读本文之前,我也做了同样的事情。所以我最终使用了这种方法。我还想了解每个模块顶部的require语句何时运行?我问题的最后一部分,你能给我回电吗?我在这个问题上陷入了困境。我的理解是(完全基于我自己的非正式观察-我从未测试过它),导入和要求在加载模块时执行。关于你在评论中发布的链接:我没有看到这种讨论——它表明使用这种方法性能更好。这可能是真的,如果性能是你最关心的,那就去做吧。我通常在编写代码时会考虑到一些其他问题:保持代码简单易读,除非我需要,否则不要包含包。谢谢回来。虽然性能可能不是我目前正在开发的应用程序的主要关注点,但考虑到我这么做只是为了学习。但我的目标是理解正确和最好的方法。关于nodejs/expressjs中的编码还有其他改进/建议吗?这是我第一次尝试使用node和mongo编写应用程序。