1 回答

TA貢獻1854條經驗 獲得超8個贊
由于所有查詢都是獨立的,因此您可以使用 并行運行它們promise.all(),代碼將如下所示:
app.post('/fetch-numbers', async (req, res) => {
? ? Promise.all([
? ? ? ? Clinic.countDocuments({}),
? ? ? ? Dentist.countDocuments({}),
? ? ? ? Booking.countDocuments({})
? ? ])
? ? .then((docCounts) => {
? ? ? ? const numbers = docCounts.reduce((a, b) => a + b, 0)
? ? ? ? res.json(numbers);
? ? })
? ? .catch(err => res.json(err));
? ? const numbers = docCounts.reduce((a, b) => a + b, 0)
? ? res.json(numbers);
});
async-await您可以通過使用with進一步使其更具可讀性Promise.all(),例如:
app.post('/fetch-numbers', async (req, res) => {
? ? try {
? ? ? ? const docCounts = await Promise.all([
? ? ? ? ? ? Clinic.countDocuments({}),
? ? ? ? ? ? Dentist.countDocuments({}),
? ? ? ? ? ? Booking.countDocuments({})
? ? ? ? ]);
? ? ? ? const numbers = docCounts.reduce((a, b) => a + b, 0)
? ? ? ? res.json(numbers);
? ? } catch(err) {
? ? ? ? res.json(err);
? ? }
});
添加回答
舉報