diff --git a/docs/uniCloud/cf-functions.md b/docs/uniCloud/cf-functions.md index 440f02442c0ad2ae7b1cfca3582e51cd3d1b1121..72ff9ef54c7ec27801ce2bf32041d048911ce753 100644 --- a/docs/uniCloud/cf-functions.md +++ b/docs/uniCloud/cf-functions.md @@ -661,6 +661,94 @@ exports.main = async function() { - 云端的云函数中使用的时区是 `UTC+0`,而不是 `UTC+8`,在云函数中使用时间时需特别注意。云函数在HBuilderX本地运行时,时区则是电脑的时区,很可能是 `UTC+8`。建议使用时间戳,可以规避时区问题。 +### 云函数递归调用@recurrenceCf +当一个云函数实例资源不能满足需求,或超时时间不够用时。比如你要给10万个用户发送的短信,而短信发送api一次只接受50个用户,那一共需要调用2000次接口。而这2000次调用不能在一个云函数中完成。这种场景就可以使用云函数递归调用,来分解任务。 + +示例代码如下: + +``` +// 当前云函数名称 send-sms-cf +'use strict'; +const db = uniCloud.database(); +const dbCmd = db.command +const userTable = db.collection('uni-id-users') +exports.main = async (event, context) => { + //执行业务逻辑 + let res = await sendSms(event.before_id) + if (res.errCode) { + return res + }else{ + // 如果没有报错,就让当前云函数 调用当前云函数(云对象同理)。注意:这里是异步的 + uniCloud.callFunction({ + name: 'send-sms-cf', + data: { + before_id: res.before_id + } + }).catch(e=>{ + console.log(e.message); + }).then(e=>{ + console.log(e.result); + }) + + // 等待500毫秒给下一个请求发出去的时间 + return await new Promise((resolve, reject) => { + setTimeout(() => { + resolve(res) + }, 500) + }) + } + + async function sendSms(before_id) { + console.log('before_id',before_id); + let where = { + phone: dbCmd.exists(true), + //..这里可以写你自己的其他条件,如超过多久没登录的用户 last_login_date < Date.now() - 3600*24*... + } + if(before_id){ + //高性能分页查询,以上一次查询的最后一条数据的id被起始id + where._id = dbCmd.gt(before_id) + } + + let res = await userTable.where(where) + .limit(50) + .orderBy("_id", "asc") + .get() + + if (!res.data.length) { + return { + errCode: 'sendSms-invalid', + errMsg: '结束,没有符合条件的接收者' + } + } + let phoneList = res.data.map(item => item.phone) + res = await uniCloud.sendSms({ + phoneList, + appid: '__UNI__xxxxxxx', + smsKey: '****************', + smsSecret: '****************', + templateId: '100**', // 请替换为自己申请的模板id + data: { + text1: 'xxx', + text2: 'xxx' + } + }) + if (res.errCode) { + return res + } + return { + errCode: 0, + before_id: res.data[res.data.length - 1]._id + } + } +}; +``` + +注意:如果不小心把递归云函数写成死循环,就把云函数的内容全部删除,重新上传覆盖即可 + + + + + ## 云函数配置 云函数除了代码,还有配置。在uniCloud web控制台可以配置;在HBuilderX项目中,云函数根目录的`package.json`也是存放配置的地方。