钉钉小程序如何把方法里面的返回值传递出去

    技术2022-08-16  142

    一、背景

    在钉钉小程序里面使用methods定义了一个方法A,在方法B中想要使用方法A里面得到的值 例如定义了方法A,方法A可以获取storage缓存,又定义了方法B,方法B调A拿到缓存后使用缓存里面的数据去请求一个接口,那么如何实现?

    二、解决方法

    1、通过一个全局变量传递

    方法B:

    scan() { my.scan({ scanType: ['qrCode', 'barCode'], success: (res) => { my.confirm({ // title: '温馨提示', content: res.code + '\n将该设备归档到自己名下?', confirmButtonText: '确认', cancelButtonText: '取消', success: (result) => { if (result.confirm == true) { this.getStorage("userInfo"); var searchUrl = this.data.baseUrl + '/beauty/updateMobileInfo?owner=' + this.data.userId + '&mobileNo=' + res.code; this.getRequest(searchUrl); this.getMobileListData(this.data.baseUrl + "/beauty/getMobile"); } else if (result.confirm == false) { console.log("用户已取消" + result.confirm) } } }); }, }); }

    方法A:

    //获取用户缓存信息 getStorage: function (key) { dd.getStorage({ key: key, success: (res) => { this.data.userId = res.data.userId }, fail: function (res) { dd.alert({ content: res.errorMessage }); } }); }

    公共部分:

    Component({ keyWord: {}, data: { baseUrl: "http://localhost:8081", name: "", userId: "" }, //storageData:{name:"",userId:""}, didMount() { var allMobileInfoUrl = this.data.baseUrl + '/beauty/getMobile'; console.log("===========" + allMobileInfoUrl) this.getMobileListData(allMobileInfoUrl) }, methods: {}})
    分析:

    先调用A的getStorag方法,此方法将缓存中的userId赋值给全局变量userId 再在B里面调用完A后(this.getstorage)发起http请求,请求参数取的全局变量userId

    注意:

    在A的getStorage方法中想将dd.getStorage中的res结果赋值给全局变量时候,使用this.data.userId=res.data.userId程序总说data是undefined,因为在dd.getStorage()函数里面无法访问到全局变量,解决方法,使用箭头函数:success: (res) => { this.data.userId = res.data.userId } 官方的写法:success: function() { dd.alert({content: ‘写入成功’}); },不能在success里面赋值给全局变量

    2、使用函数返回值

    官方给的这种方法可见可以直接拿到缓存的返回值,就可以直接在方法A中调用了。 let res = dd.getStorageSync({ key: ‘currentCity’ }); dd.alert({ content: JSON.stringify(res.data), }); 但弊端是这个是异步的方法,而我们需要即时拿到缓存数据去发起请求,不能异步,否则不准确。

    Processed: 0.013, SQL: 9