async function getServerTime() { console.log('获取时间'); const now = Date.now(); const cacheServerTimeTime = app.globalData.servertimetime || 0; const cacheServerTime = app.globalData.servertime || null; const date = new Date() const y = date.getFullYear() const m = date.getMonth() + 1 const d = date.getDate() const systemToday = y + '-' + (m < 10 ? '0' + m : m) + '-' + (d < 10 ? '0' + d : d) if (cacheServerTime && now - cacheServerTimeTime < 5 * 60 * 1000 && systemToday === cacheServerTime) { console.log('缓存servertime未过期,返回缓存servertime'); return cacheServerTime; } else { console.log('缓存servertime过期,重新获取服务器时间'); const today = await wx.cloud.callFunction({name: 'getServerTime'}); app.globalData.servertime = today.result; app.globalData.servertimetime = Date.now(); return today.result; } }这段代码在微信小程序中存在那些问题?你能指出问题,并修复问题吗?
时间: 2023-12-10 15:38:20 浏览: 161
这段代码存在以下问题:
1. 缺少`app`对象的定义,需要在代码中定义或者引入。
2. `wx.cloud.callFunction`是一个异步函数,在调用时需要使用`await`关键字。
3. 在判断缓存是否过期时,应该先判断缓存是否存在,否则会出现未定义错误。
修复后的代码如下:
```
async function getServerTime() {
const app = getApp();
console.log('获取时间');
const now = Date.now();
const cacheServerTimeTime = app.globalData.servertimetime || 0;
const cacheServerTime = app.globalData.servertime || null;
const date = new Date();
const y = date.getFullYear();
const m = date.getMonth() + 1;
const d = date.getDate();
const systemToday = y + '-' + (m < 10 ? '0' + m : m) + '-' + (d < 10 ? '0' + d : d);
if (cacheServerTime && now - cacheServerTimeTime < 5 * 60 * 1000 && systemToday === cacheServerTime) {
console.log('缓存servertime未过期,返回缓存servertime');
return cacheServerTime;
} else {
console.log('缓存servertime过期,重新获取服务器时间');
const { result } = await wx.cloud.callFunction({name: 'getServerTime'});
app.globalData.servertime = result;
app.globalData.servertimetime = Date.now();
return result;
}
}
```
阅读全文