
微信小程序
index.js onLoad: function (options) { this.test() } async test() { await app.onLogin() await this.onGetDefaultTime() //请问为什么没有等 onLogin()执行完 } --------------------------------------------- app.js async onLogin() { await wx.cloud.callFunction({ name: 'login', data: {}, success: async (res) => { console.warn("ID:" + res.result.openid) this.data.openid = res.result.openid }, }) } 谢谢!
1 Ununennium OP 写成 app.onLogin().then(this.onGetDefaultTime())也不行 |
2 jtwor 2020 年 8 月 31 日 onLogin 的回调也是异步 就是异步里面还异步 |
3 triple7 2020 年 8 月 31 日 `wx.cloud.callFunction`不要使用回调方式,改为`const result = await wx.cloud.callFunction(参数)看下。` |
4 chenluo0429 2020 年 8 月 31 日 wx.cloud.callFunction 的异步是通过 function callback 形式回调的,而不是 Promise 。通常的做法是将其转换为一般的 Promise 形式: return new Promise(resolve => { wx.cloud.callFunction({ name: 'login', data: {}, success: (res) => { resolve(); }, }); |
5 mxT52CRuqR6o5 2020 年 8 月 31 日 via Android Promise 是 callback 的封装,await/async 是 Promise 的语法糖,你要 await Promise 对象才能达到用同步写法去写异步,好好把 Promise 学明白,不然写不对的 |
6 zhlssg 2020 年 8 月 31 日 回调函数需要用 promise 包装一下 |
7 Niphor 2020 年 8 月 31 日 APP 和 PAGE 是两个不同的线程 他们是并发的,不是依次执行的 |
8 lonelymarried 2020 年 8 月 31 日 await 咋又走 success callback 了。如果要走 callback,里面要 resolve 一下,外面 await 就不要了。await 和 callback 只能选一个。 |
9 Ununennium OP @jtwor 感谢回答,您是说 wx.cloud.callFunction()也是异步吗? |
10 Ununennium OP @chenluo0429 感谢回答,不是很明白您的意思。 最后还是解决了,写成 new Promise(function (resolve) { app.onLogin(resolve); }).then(()=>this.onGetDefaultTime()) |
11 Ununennium OP @zhlssg 感谢回答,您是说这样吗 new Promise(function (resolve) { app.onLogin(resolve); }).then(()=>this.onGetDefaultTime()) |