ajax获取openid,异步环境下获取 openid的几个方法

测试几段代码,在异步环境获取 openid ,以交流探讨。

1. 小程序启动时获取

在 Page 的 onLoad 阶段调用以下函数。该函数通过调用云函数获取openid。当拿到后即设置一个变量 dataReady。该变量用来控制 wxml 页面显示,当为真时即完整显示页面。这里假定:页面完整显示后再使用openid。// index.js

Page({

data: {

openid : "",

dataReady: false,

},

onLoad: function(){

getopenid(this)

//...

},

})

function getopenid(that){

wx.cloud.callFunction({

name: getopenid,

success: res=>{

that.setData({openid: res.openid, dataReady: true})

}

})

}

// index.xmls

//

//

//   

//   

//

//

在 函数getopenid中,除了采用回调函数方式,亦可用 Promise 对象(ES6),或 async/await型函数(ES8)等方式。

2. 在其他场合获取

这时要确保使用openid的代码应出现在获取操作完成后。比如使用回调函数方式:function getopenid(){

wx.cloud.callFunction({

name: getopenid,

success: res=>{

//在这里使用openid

}

})

}

如果使用 ES6 中的 Promise 对象,就要出现在then语句块里:var p1 = new Promise(function (resolve, reject){

wx.cloud.callFunction({

name: "getopenid",

data: {para1: "", para2: ""},

success: res=>{resolve(res)},

})

p1.then(res => {

// 在这里使用 openid

}, function(res){}

)

如果使用 ES8 中的async 型函数 ,则应该出现在 await 指令之后。async getopenid function(){

lcid = await wx.cloud.callFunction()

//在这里使用openid

}

以下列出异步环境下的代码执行顺序:其中:*step i 表示由系统发起。先前各步迅速执行完后,控制权即交给系统。等到悬挂任务(PendingJob)完成后再由系统发起执行后续代码。

1. 回调函数方式// step 1

func1()

// step 4

function func1(){

// step 2

var lca = wx.cloud.callFunction({success: res=>{

// *step 5

}

})

// step 3

}

2. Promise 对象// step 1

var p1 = new Promise(function(resolve, reject){

wx.cloud.callFunction({

success: res=>{

// *step 4

resolve(res)

}

})

})

// step 2

p1.then({

// *step 5

}, {

}

)

// step 3

3. async/await 型函数// step 1

func1()

// step 3

async function func1(){

// step 2

var lca = await wx.clooud.callFunction()

// *step 4

}

欢迎批评指正。[END]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值