云开发数据库查询setData后,在onLoad中无法访问
发布于 5 年前 作者 fangtang 7287 次浏览 来自 问答

RT, 代码如下:

// miniprogram/pages/medicine_index/medicine_index.js
Page({
 
  /**
   * 页面的初始数据
   */
  data: {
    "medicine":"N/A",
  },
 
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getDbData("medicine", {}, "medicine");
    console.log("在onLoad中medicine:",this.data.medicine)
  },
 
  getDbData: function(coll_name, search_cond, data_key){
    const db = wx.cloud.database()
    var that = this;
    db.collection(coll_name).where(search_cond).get({
      success:function(res){
        that.setData({
          "medicine":res.data,
        });
        console.log("查询数据库完成:",that.data)
      }
    })
  }
})

以上代码期望:

  1. 在onLoad中调用自定义函数:getDbData

  2. 在getDbData中,调用云数据库接口从数据库中查询记录,将查询结果赋值给data中的medicine变量

  3. 之后在onLoad想要访问this.data.medicine,发现该变量没有被赋值

执行结果如下:

2 回复

onLoad: asyncfunction (options)

awaitthis.getDbData

getDbData: asyncfunction

await db.collection

试一下

异步问题 this.getDbData的  db.collection还没运行完毕  就打印了     所以自然没有值的

回到顶部