简体   繁体   English

快递承诺链错误

[英]Express promise chain error

I've written a simple express.js server that handles REST API requests and fetches data from a MongoDB database. 我编写了一个简单的express.js服务器来处理REST API请求并从MongoDB数据库中获取数据。 When I make a GET request to a specific endpoint ("localhost:8081/api/getUserData"), the promise chain doesn't work the way I want it to, and I still don't understand. 当我向特定端点(“localhost:8081 / api / getUserData”)发出GET请求时,promise链不能按照我想要的方式工作,我仍然不明白。

This is the error I get: "[TypeError: Cannot read property 'db' of undefined]" 这是我得到的错误:“[TypeError:无法读取未定义的属性'db']”

var MongoClient = require('mongodb').MongoClient;
var express = require('express');
var app = express();
var rp = require("request-promise");
var cors = require('cors');

// use it before all route definitions
app.use(cors({ origin: '*' }));

/********************** REST API FUNCTIONS **********************/
app.get('/api/getUserData', function (req, res, next) {
  var context = {};
  console.log("in api getUserData")
  context.db_url = 'mongodb://localhost:27017/test';
  openDatabaseConnection(context)
    .then(getAllUserLocations)
    .then(closeDatabaseConnection)
    .then(function (context) {
      res.send(context.userLocations)
    })
    .catch(function (error) {
      console.log("ERROR :");
      console.log(error);
    })
})
/********************** END REST API FUNCTIONS **********************/

function getAllUserLocations(context) {
  context.db.collection("test").find().toArray().then(function (err, result) {
    console.log("Received from db: " + result.length + " objects");
    context.userLocations = result;
    return context;
  });
}

function openDatabaseConnection(context) {
  console.log("Opening DB connection...");
  return MongoClient.connect(context.db_url)
    .then(function (db) {
      console.log("DB connection opened.");
      context.db = db;
      return context;
    })
}

function closeDatabaseConnection(context) {
  console.log("Closing DB connection");
  return context.db.close()
    .then(function () {
      console.log("DB connection closed");
      return context;
    })
}

/********************** STARTING SERVER **********************/
var server = app.listen(8081, function () {
  var host = server.address().address
  var port = server.address().port
  console.log("Githex server listening at http://%s:%s", host, port)
})

Any help would be appreciated, and even more with an explanation because I don't understand what I've done wrong. 任何帮助将不胜感激,甚至更多的解释,因为我不明白我做错了什么。

Thanks! 谢谢!

Just like @adeneo mentioned on the first comment, you are missing the db property. 就像第一条评论中提到的@adeneo一样,您缺少db属性。 Look at your first function: 看看你的第一个功能:

app.get('/api/getUserData', function (req, res, next) {
  var context = {};
  console.log("in api getUserData")
  context.db_url = 'mongodb://localhost:27017/test';
  openDatabaseConnection(context)
    .then(getAllUserLocations)
    .then(closeDatabaseConnection)
    .then(function (context) {
      res.send(context.userLocations)
    })
    .catch(function (error) {
      console.log("ERROR :");
      console.log(error);
    })
});

Now going through the lines within this function: 现在通过这个函数中的行:

  1. You setup context as an empty object 您将上下文设置为空对象
  2. You added a db_url property onto the object, so far you have 你在对象上添加了一个db_url属性,到目前为止你已经有了

     context = {db_url: "mongodb://localhost:27017/test} 
  3. You pass the context object into the openDatabaseConnection function 您将上下文对象传递给openDatabaseConnection函数
  4. Within the openDatabaseConnection function, you return a context object. 在openDatabaseConnection函数中,您将返回上下文对象。 This new returned object doesn't get set anywhere, it just gets returned and never used. 这个新返回的对象不会在任何地方被设置,它只是返回并且从未使用过。 You want to call the getuserlocation() function with that returned value. 您希望使用返回的值调用getuserlocation()函数。

So instead of just calling 所以不要只是打电话

.then(getAllUserConnection)

I would do 我会做

.then(function(context){getAllUserConnection(context);})

That should make use of the returned value and make sure you are using it. 这应该使用返回的值并确保您正在使用它。

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

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