目标:
在load()上使用JavaScript promises,如果数据库尚未填充,请使用数据对其进行种子设定,然后使用getWidgets()显示数据,否则,如果db已经为getWidgets()播种了数据。
代码:
const initialWidgets = [
{id: 1, color: 'Red', sprocketCount: 7, owner: 'John'},
{id: 2, color: 'Taupe', sprocketCount: 1, owner: 'George'},
{id: 3, color: 'Green', sprocketCount: 8, owner: 'Ringo'},
{id: 4, color: 'Blue', sprocketCount: 2, owner: 'Paul'}
];
require('./model');
const Widget = require('mongoose').model('WidgetModel');
function seedWidgets() {
let results = [];
Widget.find({}, function (err, collection) {
if (err) { throw err;}
if (collection.length === 0) {
initialWidgets.map(widget => {
Widget.create(widget);
});
}
})
}
export function getWidgets(req) {
let widgets = req.session.widgets;
if (!widgets) {
/// ?? seed database
/// ?? add new records to session
}
return widgets;
}
export default function load(req) {
return new Promise((resolve, reject) => {
resolve(getWidgets(req));
})
}
在load()...
中使用promises处理这三种方法的正确方法是什么?由于
答案 0 :(得分:0)
仅供参考:这是对项目的改进:
https://github.com/erikras/react-redux-universal-hot-example
承诺对我来说是新的。这有效,但我不知道这是否正确。
我会非常感谢那些知识渊博的人,然后我就我的解决方案发表意见,无论是好是坏还是有更好的事情。
const initialWidgets = [
{id: 1, color: 'Red', sprocketCount: 7, owner: 'John'},
{id: 2, color: 'Taupe', sprocketCount: 1, owner: 'George'},
{id: 3, color: 'Green', sprocketCount: 8, owner: 'Ringo'},
{id: 4, color: 'Blue', sprocketCount: 2, owner: 'Paul'}
];
require('./model');
const Widget = require('mongoose').model('WidgetModel');
function seedWidgets() {
let results = [];
return new Promise((resolve, reject) => {
Widget.find({}, (err, collection) => {
if (collection.length === 0) {
initialWidgets.map(widget => {
Widget.create(widget);
results.push(widget);
});
}
if (err) reject(err);
else resolve(results);
})
});
}
export default function load() {
return new Promise((resolve, reject) => {
resolve(getWidgets(req));
});
}
export default function getWidgets() {
return new Promise((resolve, reject) => {
seedWidgets().then((result) => {
Widget.find({}).then((result) => {
resolve(result);
})
}).catch((err) => {
reject(err);
})
});
}