微信小程序云开发小程序端获取云端数据库大于20条的方法

因为要使用同步功能,首先在所要添加功能的js页面中导入runtime.js文件,同时把runtime.js文件放入相应文件夹(runtime.js文件在附件中);
const regeneratorRuntime = require("../../lib/runtime");
直接上代码,代码中有注释,一目了然;
//本代码仅展示获取云端数据库大于20条的方法,其它功能请自行编写
Page({
​data: {
    array: [],
  },
​  async wechatauthorization() {
    var that = this;
  //由于需要同步获取数据,可能较慢,最好加入加载动画
    wx.showLoading({
      title: '加载中',
    })
   //初始化云端环境
    const db = wx.cloud.database({
      env: 'test'//填写自己的云端环境ID
    })
    //定义每次获取的条数
    const MAX_LIMIT = 20;
    //先取出集合的总数
    const countResult = await db.collection('agreement').count()
    const total = countResult.total
    //计算需分几次取
    const batchTimes = Math.ceil(total / MAX_LIMIT)
    // 承载所有读操作的 promise 的数组
    const arraypro = []
   //初次循环获取云端数据库的分次数的promise数组
    for (let i = 0; i < batchTimes; i++) {
      const promise = await db.collection('agreement').skip(i * MAX_LIMIT).limit(MAX_LIMIT).get()
     //二次循环根据获取的promise数组的数据长度获取全部数据push到arraypro数组中
      for (let j = 0; j < promise.data.length;j++){
        arraypro.push(promise.data[j])
      }
    }
    // console.log(arraypro)
    //把数据传递至页面视图
    that.setData({
      array: arraypro,
    })
    wx.hideLoading()
  },
})

 

posted @ 2022-02-20 18:01  黄浩#  阅读(675)  评论(0编辑  收藏  举报