我需要遍历数组并将每个对象保存到数据库。遍历数组并保存对象后回调
最后我需要回调一个array
的所有保存和失败的对象。
下面是我的代码:
exports.addList = (app, body, callback) => {
var savedObjects = []
var failedObjects = []
body.forEach((element, index) => {
body[index] = _.pick(element, 'userAId','userBId')
db.List.create(element).then((list) => {
savedObjects.push(element)
if (index == body.length - 1) {
callback(savedObjects, failedObjects)
}
}).catch((error) => {
if (error.name === "SequelizeUniqueConstraintError") {
failedObjects.push(element)
if (index == body.length - 1) {
callback(savedObjects, failedObjects)
}
})
})
}
上述工程的代码。有没有更好的方法来实现这一点?
你不喜欢现在如何工作?它也许值得发布到[代码评论](http://codereview.stackexchange.com/)。 –
这似乎是一种合理的方式来实现你所需要的。如果你想减少一些重复,你可以把你的完整支票放在承诺链末尾的一个'finally'调用中,并将它从'then'和'catch'处理程序中移除。 –
谢谢。我是JavaScript新手,不确定这是否正确。 @JordanBurnett我会重构保持代码干。 – user1107173