exports.main = async (event, context) => {
const tokenUrl =
'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=***&secret=***';
// uniCloud.httpclient 发起请求
const res = await uniCloud.httpclient.request(tokenUrl, {
method: 'GET',
dataType: "json"
});
//返回数据给客户端
let access_token = res.data.access_token;
const db = uniCloud.database();
var now_date = getFormatDate(0);
var next_date = getFormatDate(24 * 60 * 60 * 1000);
console.log('access_token:' + access_token);
// 从云开发数据库中查询等待发送的消息列表
const messages = await db
.collection('messages')
// 查询条件这里做了简化,只查找了状态为未发送的消息
// 在真正的生产环境,可以根据开课日期等条件筛选应该发送哪些消息
// .where({
// date: {"gte": now_date},
// })
.get();
// 循环消息列表
// 发送订阅消息
// uniCloud.httpclient 发起请求
messages.data.map(message => {
const sendUrl = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' + access_token;
let send_data = {
touser: message.data.touser,
page: "pages/index/index",
data: {
phrase1: {
value: "节活",
},
name3: {
value: message.data.nickName,
},
date5: {
value: message.data.date,
},
thing6: {
value: "节活!",
}
},
template_id: message.data.templateId,
};
console.log(send_data);
uniCloud.httpclient.request(sendUrl, {
data: send_data,
method: 'POST',
contentType: 'json',
dataType: "json",
timeout: 10000
},
function(error, response, body) {
console.log(response)
if (!error && response.statusCode == 200) {
console.log(response) // 请求成功的处理逻辑
// 发送成功后将消息的状态改为已发送
db.collection('messages')
.doc(message._id)
.update({
data: {
date: next_date,
},
});
}
}
);
})
};

2***@qq.com
- 发布:2020-12-25 23:21
- 更新:2021-01-08 17:18
- 阅读:877
2 个回复
DCloud_uniCloud_WYQ
不可以这样并发请求,会导致请求排队超时
2***@qq.com (作者)
了解,最后返回一个promise就好了