2 回答

TA貢獻(xiàn)1862條經(jīng)驗(yàn) 獲得超7個(gè)贊
正在Array.map()返回一個(gè)承諾數(shù)組,您可以使用Promise.all(). 在地圖內(nèi)部,您應(yīng)該使用throw new Error()break out of map - 將引發(fā)此錯(cuò)誤Promise.all(),然后您可以捕獲它并將錯(cuò)誤返回給客戶(hù)端(或吞下它等)。
這是您的模式的更正版本,解決了 Promise 結(jié)果。
const { organizations } = req.body;
try {
// use Promise.all to resolve the promises returned by the async callback function
const organizationsArray = await Promise.all(
// this will return an array of promises
organizations.map(async (organization) => {
const organizationExists = await Organization.findByPk(organization, {
attributes: ['id'], // we only need the ID
raw: true, // don't need Instances
});
if (!organizationExists) {
// don't send response inside the map, throw an Error to break out
throw new Error(`Organization ${organization} does not exists!`);
}
// it does exist so return/resolve the value for the promise
return {
course_id: id,
organization_id: organization,
};
})
);
// if we get here there were no errors, create the records
await CoursesOrganizations.bulkCreate(organizationsArray);
// return a success to the client
return res.json({ success: true });
} catch (err) {
// there was an error, return it to the client
return res.status(400).json({ error: err.message });
}
Organizations這是一個(gè)重構(gòu)版本,通過(guò)在一個(gè)查詢(xún)中獲取所有內(nèi)容然后進(jìn)行檢查/創(chuàng)建插入,速度會(huì)更快一些Course。
const { Op } = Sequelize;
const { organizations } = req.body;
try {
// get all Organization matches for the IDs
const organizationsArray = await Organization.findAll({
attributes: ['id'], // we only need the ID
where: {
id: {
[Op.in]: organizations, // WHERE id IN (organizations)
}
},
raw: true, // no need to create Instances
});
// create an array of the IDs we found
const foundIds = organizationsArray.map((org) => org.id);
// check to see if any of the IDs are missing from the results
if (foundIds.length !== organizations.length) {
// Use Array.reduce() to figure out which IDs are missing from the results
const missingIds = organizations.reduce((missingIds, orgId) => {
if (!foundIds.includes(orgId)){
missingIds.push(orgId);
}
return missingIds;
}, []); // initialized to empty array
throw new Error(`Unable to find Organization for: ${missingIds.join(', ')}`);
}
// now create an array of courses to create using the foundIds
const courses = foundIds.map((orgId) => {
return {
course_id: id,
organization_id: orgId,
};
});
// if we get here there were no errors, create the records
await CoursesOrganizations.bulkCreate(courses);
// return a success to the client
return res.json({ success: true });
} catch (err) {
// there was an error, return it to the client
return res.status(400).json({ error: err.message });
}

TA貢獻(xiàn)1875條經(jīng)驗(yàn) 獲得超3個(gè)贊
如果你有一個(gè) ID 數(shù)組并且你想檢查它們是否存在你應(yīng)該使用 (in) 運(yùn)算符,這使得你只訪(fǎng)問(wèn)數(shù)據(jù)庫(kù)一次并一次獲取所有記錄(而不是獲取它們一個(gè)一個(gè)循環(huán)),在你得到這些記錄后,你可以檢查它們的長(zhǎng)度以確定它們是否都存在。
const { Op } = require("sequelize");
let foundOrgs = await Organization.findAll({
where: {
id: {
[Op.in]: organizationsArray,
}
}
});
添加回答
舉報(bào)