【发布时间】: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 更适合?我失去了帮助?
【问题讨论】:
-
你试过wait.for吗? github.com/luciotato/waitfor
标签: javascript node.js mongoose