用promise包装getUserInfo 获取不到数据
Bug:
* 用promise包装getUserInfo 获取不到数据
* 复现
wx.login({ success: res => next(res), fail: err => error(err) }) }), wxGetUserInfo: () => new Promise((next, error) => { wx.getUserInfo({ success:res=>next(res), fail:err=>error(err) }) }), /** * 生命周期函数--监听页面显示 */ onShow: function () { this .wxLogin().then(data => { console.log(data) //{errMsg: "login:ok", , code: "adkjdkjdsljdslkdjlkds"} this .wxGetUserInfo(info => console.log(info)) // empty })
|
3 回复
看你的代码似乎没问题,是不是授权问题,有没有返回错误消息?
我的代码给你参考一下,是TypeScript 2 代码,编译成 ES5 后,测试运行正常:
class Login { private isLoginFail = false ; private userInfo!: ILoginUserInfo; public getUserInfo(): ILoginUserInfo { return this .userInfo; } public login(skipOwnLogin: boolean) { return this .loginPromise(skipOwnLogin).then((v) => { if (skipOwnLogin) { return v; } const userInfo = (v as any); if (userInfo.isEmployee) { userInfo.name = "" ; userInfo.phone = "" ; } this .userInfo = userInfo; console.log( "login success" ); console.log(userInfo); return userInfo; }). catch ((e) => { console.error( "login faile[save user info]" , e); this .isLoginFail = true ; Promise.reject(e); }); } private async loginPromise(skipOwnLogin: boolean): Promise<WeApp.UserInfo | ILoginUserInfo> { try { // wechat login const wxLoginCodeRes = await new Promise<WeApp.LoginResult>((resolve, reject) => { wx.login({ success: resolve }); }); if (!wxLoginCodeRes.code) { throw new Error(`wx.login error:${wxLoginCodeRes.errMsg}`); } // wechat get userinfo const wxInfoRes = await new Promise<WeApp.UserInfo>((resolve, reject) => { wx.getUserInfo({ success: resolve, withCredentials: true , }); }); if (skipOwnLogin) { return wxInfoRes; } // own server login const ownInfoRes = await (requestPromise({ data: { code: wxLoginCodeRes.code, encryptedData: wxInfoRes.encryptedData, iv: wxInfoRes.iv }, method: "POST" , url: getRequestUrl( "/wx/xcx" ), }) as Promise<{ data: ILoginResponse; statusCode: number; headers: {} }>); if (ownInfoRes.statusCode !== 200) { throw new Error(`ownServer.login error:http request status code is ${ownInfoRes.statusCode}`); } if (ownInfoRes.data.errCode) { throw new Error(`ownServer.login error:${ownInfoRes.data}`); } // TODO remove var const a = { ...wxInfoRes.userInfo, ...ownInfoRes.data }; return a; } catch (e) { console.error(e); Promise.reject(e); } throw new Error( "Programe Logic miss." ); } } |
推荐我开源的 https://github.com/youngjuning/wxPromise ,支持小程序API promise化、ES7 async await 等函数、ES8 finally 、一揽子正则验证和一些解决方案函数。开发不易,喜欢的话给一个星星