【问题标题】:ES6 Promises in express app not properly resolving dataExpress 应用程序中的 ES6 Promise 无法正确解析数据
【发布时间】:2017-03-30 03:53:43
【问题描述】:

我正在编写一个带有 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);
      });
    }
  );
};

我是新的承诺,所以任何提示/建议将不胜感激!

【问题讨论】:

  • 你需要 return 来自你的 then 处理程序的东西。

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


【解决方案1】:

确保从您的 then 处理程序返回一个值。下面的代码通过使用箭头函数的简洁主体形式来做到这一点。

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

【讨论】:

    猜你喜欢
    • 2019-12-26
    • 2020-11-16
    • 2018-07-31
    • 1970-01-01
    • 2019-02-10
    • 1970-01-01
    • 1970-01-01
    • 2016-06-21
    • 2014-01-13
    相关资源
    最近更新 更多