微信小程序如何抽出model层,避免重复造轮子

来源:互联网 发布:网络21 编辑:程序博客网 时间:2024/06/05 20:54
今天 学生小程序,需要抽出一些常用的方法,以免可以实现一处遍写,多处复用的目地。一般我们编写小程序都是在一个js文件中完成以下的请求
然后绑定数据。

var baseUrl = 'http://www.thinkphp50.com/index.php/api/v1';

wx.request({
url: baseUrl + '/banner/' + id,
header: { 'content-type': 'application/json'},
method: 'GET',
dataType: 'json',
success: function(res) {
this.setData()//这里省略
},
})

这个虽看似方便,但方法复用性差。
所以我们抽出了一个常用的方法,放到一个公共文件中,但wx.request方法都是异步的,这个就造成了,异步方法里的sueecss方法未返回数据,主调用方法
就调用完成了。
那有什么办法解决嘛?答案当然是有的,那就是用回调函数。

class Home{
constructor(){

}
getBannerDate(id,callback){
wx.request({
url: baseUrl + '/banner/' + id,
header: { 'content-type': 'application/json'},
method: 'GET',
dataType: 'json',
success: function(res) {
callback(res)
},
})
}
}

如上方法中,用回调callback方法返回值。


则在以下主调方法中,就可以拿到回调的res数据。
_loadData:function(){
var id=1;
var data = home.getBannerDate(id,(res)=>{
console.log(123456789);
console.log(res);
});
},

至此,就可以愉快的继续编程了