云函数云端测试时显示如下:
调用状态
失败, ret code 1
返回结果
{“errorCode”:1,“errorMessage”:“user code exception caught”,“stackTrace”:“TypeError: Cannot read property ‘length’ of undefined\n at Runtime.exports.main [as handler] (/var/user/index.js:26:35)\n at process._tickCallback (internal/process/next_tick.js:68:7)”}
代码部分:
// 云函数入口文件
const cloud = require(‘wx-server-sdk’)
cloud.init()
//云数据库相应的初始化
const db = cloud.database()
const axios = require(‘axios’)
const URL = 'https://apis.imooc.com/personalized?icode=37B746D45184CA07’
const playlistCollection = db.collection(‘playlist’)
// 云函数入口函数
exports.main = async (event, context) => {
const {data} = await axios.get(URL)
//读取Playlist集合里面的数据
const list = playlistCollection.get()
if (data.code >= 1000) {
// msg是如果错误取这个参数显示
console.log(data.msg)
return 0
}
const playlist = data.result
// 歌单数据去重
const newData = []
for (let i = 0, len1 = playlist.length; i < len1; i++) {
let flag = true
for (let j = 0,len2 = list.data.length; j < len2; j++) {
if (playlist[i].id===list.data[j].id) {
flag = false
break
}
}
if (flag) {
newData.push(playlist[i])
}
}
// 将数据playlist获得的插入云数据库
if (newData.length>0) {
await playlistCollection.add({
data:[…newData]
}).then((res) => {
console.log(‘插入成功’)
}).catch((err) => {
console.log(err)
console.error(‘插入失败’)
})
}
return newData.length
}