请问为什么 await 不起作用?

2020-08-31 14:42:21 +08:00
 lithium148

微信小程序

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
  },
})
}

谢谢!

1323 次点击
所在节点    问与答
11 条回复
lithium148
2020-08-31 14:43:29 +08:00
写成 app.onLogin().then(this.onGetDefaultTime())也不行
jtwor
2020-08-31 14:47:19 +08:00
onLogin 的回调也是异步 就是异步里面还异步
triple7
2020-08-31 14:51:30 +08:00
`wx.cloud.callFunction`不要使用回调方式,改为`const result = await wx.cloud.callFunction(参数)看下。`
chenluo0429
2020-08-31 15:00:41 +08:00
wx.cloud.callFunction 的异步是通过 function callback 形式回调的,而不是 Promise 。通常的做法是将其转换为一般的 Promise 形式:
return new Promise(resolve => {
wx.cloud.callFunction({
name: 'login',
data: {},
success: (res) => {
resolve();
},
});
mxT52CRuqR6o5
2020-08-31 15:05:14 +08:00
Promise 是 callback 的封装,await/async 是 Promise 的语法糖,你要 await Promise 对象才能达到用同步写法去写异步,好好把 Promise 学明白,不然写不对的
zhlssg
2020-08-31 15:06:35 +08:00
回调函数需要用 promise 包装一下
Niphor
2020-08-31 15:09:04 +08:00
APP 和 PAGE 是两个不同的线程 他们是并发的,不是依次执行的
lonelymarried
2020-08-31 15:09:14 +08:00
await 咋又走 success callback 了。如果要走 callback,里面要 resolve 一下,外面 await 就不要了。await 和 callback 只能选一个。
lithium148
2020-09-02 14:24:16 +08:00
@jtwor 感谢回答,您是说 wx.cloud.callFunction()也是异步吗?
lithium148
2020-09-02 14:25:55 +08:00
@chenluo0429 感谢回答,不是很明白您的意思。
最后还是解决了,写成
new Promise(function (resolve) {
app.onLogin(resolve);
}).then(()=>this.onGetDefaultTime())
lithium148
2020-09-02 14:28:40 +08:00
@zhlssg 感谢回答,您是说这样吗 new Promise(function (resolve) {
app.onLogin(resolve);
}).then(()=>this.onGetDefaultTime())

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/702820

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX