我最近开始使用 Sequelize 并尝试为 db 访问制作一个包装类。
我在创建对象后立即调用 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 方法从 card.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));
}
我有一种感觉,这就是问题所在(在我看到 createCardTable 的确认之前,console.log(this.cards) 首先运行并显示一个空列表)
.then((cards) =>
cards.map(c => c.get('name')).filter(c => (c && c != `''s`))
.forEach(c => this.createCardTable(c))
)
我认为对 createCardTable 的调用会立即解决并导致链过早地继续。我应该如何返回有效的 promise 以继续链条?
(我也喜欢关于如何清理我非常丑陋的 Promise 用法的建议)
最佳答案
我想出了对 promise 链中麻烦环节的正确替代
新的:
.then((cards) =>
Promise.map(cards.map(c => c.get('name')).filter(c => (c && c != `''s`)),
c => this.createCardTable(c))
)
(这是使用蓝鸟 promise )
关于javascript - 将一系列 promise 集成到现有链中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50974215/