收藏
回答

云开发数据库查询setData后,在onLoad中无法访问

框架类型 问题类型 API/组件名称 终端类型 微信版本 基础库版本
小程序 Bug 云开发 工具 6.7.3 2.2.5

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 个回答

  • 2019-10-27

    onLoad: asyncfunction (options)

    awaitthis.getDbData

    getDbData: asyncfunction

    await db.collection

    试一下

    2019-10-27
    有用
    回复
  • 半寸灰
    半寸灰
    2018-10-28

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

    2018-10-28
    有用
    回复 4
    • along
      along
      2018-10-28

      那怎样可以确保在onLoad中等待异步执行完毕之后再继续走下一步呢

      2018-10-28
      回复
    • 半寸灰
      半寸灰
      2018-10-28回复along

      这样也可以  suc加了个suc 回调  写成

      promise

      也可以麻烦点而已


        onLoad: function (options) {

          this.getDbData("medicine", {}, "medicine",function(res){

      console.log("在onLoad中medicine:",res)

      });

          

        },

       

        getDbData: function(coll_name, search_cond, data_key,suc){

          const db = wx.cloud.database()

          var that = this;

          db.collection(coll_name).where(search_cond).get({

            success:function(res){

              that.setData({

                "medicine":res.data,

              });

              suc(res);

              console.log("查询数据库完成:",that.data)

            }

          })

        }


      2018-10-28
      回复
    • along
      along
      2018-10-29回复半寸灰

      非常感谢,我用这个方法再试下

      2018-10-29
      回复
    • 2019-03-20回复along

      兄弟你成功了吗,小白请教suc是怎么写的

      2019-03-20
      回复
登录 后发表内容