【发布时间】:2021-01-10 17:27:05
【问题描述】:
使用:MongoDB、Express、Mongoose、NodeJs。
我目前有一个 seedDB 函数,它需要几个月的数组并为“月份”集合播种。看起来像这样:
const monthData = [{
month: 'January',
shifts: []
},
{
month: 'February',
shifts: []
},
{
month: 'March',
shifts: []
},
{
month: 'April',
shifts: []
},
{
month: 'May',
shifts: []
},
{
month: 'June',
shifts: []
},
{
month: 'July',
shifts: []
},
{
month: 'August',
shifts: []
},
{
month: 'September',
shifts: []
},
{
month: 'October',
shifts: []
},
{
month: 'November',
shifts: []
},
{
month: 'December',
shifts: []
}
];
function seedDB() {
for (entry of monthData) {
Month.create(entry, (err, created) => {
if (err) console.log(err);
else console.log(created);
})
}
}
问题是我需要按顺序播种几个月(使用这种方法并不总是发生这种情况),所以我觉得异步函数可能在这里工作,这告诉它只能提前创建下个月上个月播种时。
我看过无数关于 Promise 和 async await 的教程,但我仍然不完全理解如何应用这些逻辑。如果有人可以展示和解释我当前代码的异步/承诺替代方案,我将不胜感激......
【问题讨论】:
标签: javascript node.js mongodb mongoose async-await