ES6承诺快递应用程序无法正确解析数据

时间:2017-03-29 19:03:05

标签: mongodb express mongoose ecmascript-6 es6-promise

我正在编写一个带有ES6承诺的异步函数,1)保存用户的查询参数2)使用mongoose从mongodb获取数据,3)将json操作到DSL,4)并查询另一个数据库它。 mongoose": "^4.7.7"

//myController.js    
const myQuery = require('../models/myQuery_model');
require('mongoose').Promise = global.Promise
const uuidV4 = require('uuid/v4');


exports.saveNewQuery = function(req, res, next) {

  const rawQuery = req.body;
  const queryToStore = new myQuery(rawQuery);
  const uid = uuidV4();
  const queryToStore.uid = uid

  queryToStore.save().then(() => {
      fetchQueryFromMongo(uid);

    }).then((storedQuery) => {
      compileQueryToString(storedQuery);

    }).then((queryString) => {
      fetchResultsFromOtherDb(queryString);

    }).then((results) => {
      res.json({ results });

    }).catch((error) => {

      console.log(error)
    })
  }

目前我无法解决mongodb第2步的响应。但是,控制器继续compileQueryToString而不是从fetchQueryFromMongo

中捕获错误
// fetchQueryFromMongo.js
const myQuery = require('../models/myQuery');
require('mongoose').Promise = global.Promise

module.exports = (uid) => {
  return new Promise(
    (resolve, reject) => {
      myQuery.find({ uid }).then((err, res) => {

        if (err) {
          reject(err);
        }
        console.log('response success!')
        resolve(res);
      });
    }
  );
};

我是承诺的新手,所以任何提示/建议都会受到赞赏!

1 个答案:

答案 0 :(得分:1)

确保从then处理程序返回一个值。下面的代码通过使用箭头函数的简洁体形来完成此任务。

queryToStore.save()
  .then(()          => fetchQueryFromMongo(uid))
  .then(storedQuery => compileQueryToString(storedQuery))
  .then(queryString => fetchResultsFromOtherDb(queryString))
  .then(results     => res.json({ results }))
  .catch(console.log);