const cloud = require('wx-server-sdk') cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) const db = cloud.database() const _ = db.command exports.main = async (event, context) => { console.log(event) const usersID = event.usersID; const usersIDres = await db.collection('usersdatas').where({_id: usersID}).get() const threepartysid = usersIDres.data[0].threepartysid const allidRes = await db.collection('usersinternet').where({_id: _.in(threepartysid) }) .orderBy('isGroupRegister','desc') .orderBy('isGroupMember','desc') .orderBy('startdate','desc') .orderBy('closedate','desc') .skip(event.length) .limit(event.limit) .get() const allid = allidRes.data return allid; // 返回对象 }请优化这段代码
时间: 2023-12-19 13:05:48 浏览: 304
深入理解webpack process.env.NODE_ENV配置
以下是代码的优化建议:
1. 将云函数的初始化操作移到函数外部,避免每次调用云函数时都要初始化一次。
2. 考虑使用 Promise.all() 并行查询多个集合,提高查询效率。
3. 可以使用聚合查询来实现多条件排序,避免使用多次 orderBy() 语句。
4. 建议使用 const 替代 let 来声明只读变量。
优化后的代码如下:
```js
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
const db = cloud.database()
const _ = db.command
// 查询用户数据和用户关联的第三方ID
async function getUsersDataAndThreepartysid(usersID) {
const usersDataRes = await db.collection('usersdatas').doc(usersID).get()
const threepartysid = usersDataRes.data.threepartysid || []
return { threepartysid }
}
// 查询用户关联的第三方ID对应的互联网数据
async function getInternetData(threepartysid, length, limit) {
const internetDataRes = await db.collection('usersinternet')
.where({ _id: _.in(threepartysid) })
.aggregate()
.sort({
isGroupRegister: -1,
isGroupMember: -1,
startdate: -1,
closedate: -1
})
.skip(length)
.limit(limit)
.end()
const allid = internetDataRes.list
return allid
}
exports.main = async (event, context) => {
console.log(event)
const { usersID, length, limit } = event
// 并行查询用户数据和用户关联的第三方ID
const { threepartysid } = await getUsersDataAndThreepartysid(usersID)
// 并行查询用户关联的第三方ID对应的互联网数据
const allid = await getInternetData(threepartysid, length, limit)
return allid
}
```
阅读全文