【发布时间】:2019-10-26 05:15:31
【问题描述】:
我正在尝试使用 Sequalize ORM 在数据库中创建新行。我收到了来自req.query.collections 的一系列集合。对于每个集合,我需要创建一个新的userCollection。如果没有创建 userCollections,我想以内部服务器错误(第 41 行)进行响应,否则返回带有新创建的 userCollections 的对象数组。
问题是,当我从 Postman 发出测试请求时,我不断收到内部服务器错误。当我检查我的数据库时,我看到那些 userCollections 已创建,所以没有发生错误。
我知道为什么会这样:因为userCollection.build({ stuff }).save() 返回了一个承诺。因此,当我尝试从 .then() 语句中 console.log userCollections 时,我得到一个包含新创建的集合的数组,就像我应该做的那样。但到那时服务器已经响应内部服务器错误。
这是我的功能代码:
exports.addCollections = async (req, res, next) => {
const libraryId = req.params.libraryId;
const collections = req.query.collections;
if (!collections)
next(Boom.forbidden());
const userCollections = [];
collections.forEach(async (collectionId, index) => {
const collection = await Collection.findByPk(collectionId);
if (!collection)
return next(Boom.notFound());
userCollection.build({
user_id: req.user.id,
library_id: libraryId,
public_collection_id: collection.id,
title: collection.title,
description: collection.description
})
.save()
.then(newUserCollection => {
userCollections.push(newUserCollection.get({ plain: true }));
// should be printed first, but comes second
// prints out the array with newly created record
console.log(userCollections);
})
.catch(error => {
console.log(error);
});
});
// should be printed second, but comes first
// prints out empty array
console.log(userCollections);
if (userCollections.length === 0) {
next(Boom.internal());
}
res.json(userCollections);
}
【问题讨论】:
标签: node.js asynchronous foreach promise sequelize.js