避免与猫鼬回调地狱

时间:2014-08-07 10:40:50

标签: javascript node.js mongoose

我从节点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!
  });
})

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

2 个答案:

答案 0 :(得分: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);
});

答案 1 :(得分:1)

以下是另一个如何通过承诺来实现的例子:

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);
});

我建议您阅读有关承诺的文章:http://www.html5rocks.com/en/tutorials/es6/promises/