// 云函数入口文件
const cloud = require('wx-server-sdk')
const xlsx = require('node-xlsx')
cloud.init({
env: cloud.DYNAMIC_CURRENT_ENV
})
// 云函数入口函数excel 操作
exports.main = async (event, context) => {
const db = cloud.database()
// console.log("进入云函数",event)
//通过fileId下载云存储里的文件
const excelres = await cloud.downloadFile({
fileID : event.fileId
})
const buffer = excelres.fileContent
const tasks = [] //用来存储所有等添加数据操作
//解析excel文件里等数据
var sheets = xlsx.parse(buffer);//获取到所有sheets
sheets.forEach(function(sheet){
for (var rowId= 0 ; rowId < sheet['data'].length ; rowId++){
var row = sheet['data'][rowId];//第几行数据
console.log("当前行",rowId,row)
if (rowId > 0 && row){
let options = ""
let optionsOrde = ['A','B','C','D','E','F']
let answer = ''
let ishad = ''
//重复的题目不再添加
db.collection('question').where({
title:row[0].trim()
}).count().then((res1)=>{
console.log(res1)
if(res1.total === 0){
console.log('new',rowId)
//选项 str {{key:A,val=answerA},{key:B,val=answerB}}
for(let i= 1;i <= 5;i++){
if(row[i]){
let str =row[i].toString()
// console.log(typeof(str))
str = str.replace(/(^\s*)|(\s*$)/g, '')
options = options + "{\"key\":\"" + optionsOrde[i-1] + "\",\"val\"" + ":" + "\"" + str + "\"}" + ","
}
}
//在数据库中插入数据
options = options.replace(/(^\s*)|(\s*$)/g, '');
options = options.trim()
answer = answer.trim()
const promise = db.collection('question').add({
data: {
title:row[0].trim(),
options:"{\"optionlist\":[" + options.substring(0,options.length-1) + "]}",
answer:row[8].trim(),
type:row[7],
course:row[6],
create_date:db.serverDate()
}
}).then((res) =>{
if(res.data._id){
tasks.push(promise)
}
}).catch(function(err) {
return err
})
}
return tasks
})
.catch(function(err) {
return err
})
}
}
});
let result = tasks.reduce((prev,next)=>prev.then(()=>next()),Promise.resolve())
result.then(res1 => {
return res1
})
//return result
}
建议使用manage-sdk完成此操作。https://docs.cloudbase.net/api-reference/manager/node/database.html#import
帮你搜了一下,只搜到一个await,就知道大概率是异步问题了。