我最近开始使用Sequelize,正在尝试制作用于数据库访问的包装器类。
创建对象后立即调用connect方法。
connect() {
this.db = new Sequelize("sqlite:"+this.fp);
return this.db.authenticate()
.then(()=>console.log('Connected to:', this.fp))
.then(()=>this.Card = this.db.define('card', { name: Sequelize.STRING }))
.then(()=>this.Card.sync({ force: false }))
.then(()=>this.Card.findAll())
.then((cards) =>
cards.map(c => c.get('name')).filter(c => (c && c != `''s`))
.forEach(c => this.createCardTable(c))
).then(()=>console.log('this.cards:', this.cards))
.then(()=>this.db)
.catch(err=>console.log('Error connecting to database:', err));
}
connect方法从cards.map()调用createCardTable
createCardTable(card) {
const newTable = this.db.define(card,
{entry: Sequelize.STRING, content: Sequelize.STRING},
{freezeTableName: true});
return newTable.sync({ force: false })
.then(()=>this.cards[card] = newTable)
.then(()=>console.log('created table:', card))
.catch(err=>console.log('Error creating table:', err));
}
我感觉这就是问题所在(console.log(this.cards)首先运行并显示一个空列表,然后我看到对createCardTable的确认)
.then((cards) =>
cards.map(c => c.get('name')).filter(c => (c && c != `''s`))
.forEach(c => this.createCardTable(c))
)
我认为对createCardTable的调用会立即解决,并导致链过早地继续。我应该如何退还有效的诺言以继续连锁?
(我也很喜欢有关如何清理我非常丑陋的诺言的建议)
答案 0 :(得分:0)
我想出了对Promise链中麻烦链接的适当替代方法
新功能:
.then((cards) =>
Promise.map(cards.map(c => c.get('name')).filter(c => (c && c != `''s`)),
c => this.createCardTable(c))
)
(这是使用蓝鸟的承诺)