RT, 代码如下:
// miniprogram/pages/medicine_index/medicine_index.jsPage({ /** * 页面的初始数据 */ 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) } }) }}) |
以上代码期望:
在onLoad中调用自定义函数:getDbData
在getDbData中,调用云数据库接口从数据库中查询记录,将查询结果赋值给data中的medicine变量
之后在onLoad想要访问this.data.medicine,发现该变量没有被赋值
执行结果如下:

onLoad: asyncfunction(options)awaitthis.getDbDatagetDbData: asyncfunctionawait db.collection试一下
异步问题
this.getDbData的 db.collection还没运行完毕 就打印了 所以自然没有值的那怎样可以确保在onLoad中等待异步执行完毕之后再继续走下一步呢
这样也可以 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()varthat =this;db.collection(coll_name).where(search_cond).get({success:function(res){that.setData({"medicine":res.data,});suc(res);console.log("查询数据库完成:",that.data)}})}非常感谢,我用这个方法再试下
兄弟你成功了吗,小白请教suc是怎么写的