我需要迭代一个数组并将每个对象保存到数据库中。
最后,我需要一个回调,其中包含所有已保存和失败的对象的数组
。
下面是我的代码:
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)
}
})
})
}
上面的代码有效。有没有更好的方法来实现这一点?
最佳答案
我建议使用 Promise.all()
使用以下方法并行运行db.List.create()
,因为它将返回一个Promise
。通过mapping将 body
数组元素添加到 Promises
中,您可以获得更好的性能,因为它们将并行运行(并且不必跟踪 complete
计数)。
exports.addList = (app, body, callback) => {
var savedObjects = [];
var failedObjects = [];
Promise.all(
// map the array to return Promises
body.map(element => {
const list = _.pick(element, 'userAId','userBId');
return db.List.create(list)
.then(() => savedObjects.push(list))
.catch((error) => {
if (error.name === 'SequelizeUniqueConstraintError') {
failedObjects.push(list)
}
})
})
)
// when all Promises have resolved return the callback
.then(() => callback(savedObjects, failedObjects));
}
关于javascript - 迭代数组并保存对象后的回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41130372/