【问题标题】:Avoid callbackHell with mongoose用猫鼬避免回调地狱
【发布时间】:2015-12-17 20:43:55
【问题描述】:

我从 node mongoose 等开始...我是一个好学生,所以我关注文档:http://mongoosejs.com/docs/populate.html

使用这种语法一段时间后,我遇到了臭名昭著的回调地狱。在阅读了很多关于如何避免这种情况的信息后,我决定采用承诺方式^^。异步模块也很诱人,但我不知道它是否适合我想要实现的目标。

我只想保存一个包含所有相应参考的对象。 根据我们拥有的文档:

    var mongoose = require('mongoose')
  , Schema = mongoose.Schema

var personSchema = Schema({
  _id     : Number,
  name    : String,
  age     : Number,
  stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});

var storySchema = Schema({
  _creator : { type: Number, ref: 'Person' },
  title    : String,
  fans     : [{ type: Number, ref: 'Person' }]
});

var Story  = mongoose.model('Story', storySchema);
var Person = mongoose.model('Person', personSchema);

为了保存参考我使用:

var aaron = new Person({ _id: 0, name: 'Aaron', age: 100 });

aaron.save(function (err) {
  if (err) return handleError(err);

  var story1 = new Story({
    title: "Once upon a timex.",
    _creator: aaron._id    // assign the _id from the person
  });

  story1.save(function (err) {
    if (err) return handleError(err);
    aaron.stories.push(story1); // I added those two lines
    aaron.save(callback); // in order to save the refs to children
    // thats it!
  });
})

如何以正确的方式使用 Promise 实现相同的目标?或者也许 Async 更适合?我失去了帮助?

【问题讨论】:

标签: javascript node.js mongoose


【解决方案1】:

TBH 非常冗长,不确定是否有更短的方法来处理这个问题

试试这个? (可能在语法上不准确.. 即时输入)

var save = function(aaron){ 
   return new RSVP.Promise(function(resolve, reject){
     aaron.save(function(err){
      if(err){
        reject(err); 
      }else{
        resolve(aaron);
      }
     });
   });
};

var addStory = function(aaron{
  return new RSVP.Promise(function(resolve, reject){
     var story1 = new Story({
      title: "Once upon a timex.",
      _creator: aaron._id    // assign the _id from the person
     });
     story1.save(function(err){
      if(err){
        reject(err);
      }else{
        resolve(story1, arron);
      }
     });
  });
};

//then to exec the promises
save(arron).then(function(arron){
 addStory(arron);
}).then(function(story1, arron)){
  // tell the story?
}).catch(function(err){
    handleError(err);
});

编辑

这应该让它简短

var saves = function(objToSave){
  return new RSVP.Promise(function(resolve, reject){
    objToSave.save(function(err){
      if(err){
        reject(err);
      }else{
        resolve(objToSave);
      }
   })
  });
}

var _scope = this;
saves(arron).then(function(arron){
   var story1 = new Story({
     title: "Once upon a timex.",
     _creator: aaron._id    // assign the _id from the person
   });

  _scope.saves(story1)
}).then(function(story1){
  //do something with the story
}).catch(function(err){
  handleError(err);
});

【讨论】:

  • 什么是 TBH ?我的目标是找到实现这种节省的最佳方法;)。如果您知道任何其他方式来做到这一点,我会很高兴在这里。
  • TBH 是“诚实”的缩写。那里的代码将使用 RSVP 承诺完成这项工作。您也许可以使 RSVP 创建更通用以进行保存,但代码应该可以工作。
  • :$ - 为 TBH 感到羞愧 - 是的,它比我尝试的要好得多。
【解决方案2】:

这是另一个使用 Promise 的例子:

function save(obj) {
    return new Promise(function (resolve, reject) {
        obj.save(function (err) {
            if (err) {
                reject(err);
            } else {
                resolve(obj);
            }
        });
    });
}

var aaron = new Person({ _id: 0, name: 'Aaron', age: 100 });

save(aaron).then(function (savedAaron) {
    var story1 = new Story({
        title: 'Once upon a timex.',
        _creator: savedAaron._id
    });
    return save(story1);
}).then(function (savedStory) {
    aaron.stories.push(savedStory);
    return aaron.save(callback);
}).catch(function (err) {
    handleError(err);
});

我推荐阅读这篇关于 Promise 的文章:http://www.html5rocks.com/en/tutorials/es6/promises/

【讨论】:

  • 嗯,这是一个不错的!但我可能会再次进入回调地狱,然后在 then 中使用 then 等等。愚蠢的问题:新的 RSVP.Promise == 新的承诺?
  • 存在多个库,它们有很多共同点,但它们的 API 也存在差异。我个人喜欢 lib es6-promise。它是 ES6 Promises 的 polyfill 和 rsvp.js 的子集(另见 html5rocks.com/en/tutorials/es6/promises/…
  • @Su4p 有点晚了,但我已经更新了我的答案:There no then inside then了。
猜你喜欢
  • 2017-05-08
  • 2020-12-24
  • 1970-01-01
  • 1970-01-01
  • 2017-08-18
  • 2016-03-27
  • 2015-08-01
  • 2018-09-11
  • 1970-01-01
相关资源
最近更新 更多