V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
lithium148
V2EX  ›  问与答

请问为什么 await 不起作用?

  •  
  •   lithium148 · 2020-08-31 14:42:21 +08:00 · 1313 次点击
    这是一个创建于 1336 天前的主题,其中的信息可能已经有所发展或是发生改变。

    微信小程序

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

    谢谢!

    11 条回复    2020-09-02 14:28:40 +08:00
    lithium148
        1
    lithium148  
    OP
       2020-08-31 14:43:29 +08:00
    写成 app.onLogin().then(this.onGetDefaultTime())也不行
    jtwor
        2
    jtwor  
       2020-08-31 14:47:19 +08:00
    onLogin 的回调也是异步 就是异步里面还异步
    triple7
        3
    triple7  
       2020-08-31 14:51:30 +08:00
    `wx.cloud.callFunction`不要使用回调方式,改为`const result = await wx.cloud.callFunction(参数)看下。`
    chenluo0429
        4
    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
        5
    mxT52CRuqR6o5  
       2020-08-31 15:05:14 +08:00 via Android
    Promise 是 callback 的封装,await/async 是 Promise 的语法糖,你要 await Promise 对象才能达到用同步写法去写异步,好好把 Promise 学明白,不然写不对的
    zhlssg
        6
    zhlssg  
       2020-08-31 15:06:35 +08:00
    回调函数需要用 promise 包装一下
    Niphor
        7
    Niphor  
       2020-08-31 15:09:04 +08:00
    APP 和 PAGE 是两个不同的线程 他们是并发的,不是依次执行的
    lonelymarried
        8
    lonelymarried  
       2020-08-31 15:09:14 +08:00
    await 咋又走 success callback 了。如果要走 callback,里面要 resolve 一下,外面 await 就不要了。await 和 callback 只能选一个。
    lithium148
        9
    lithium148  
    OP
       2020-09-02 14:24:16 +08:00
    @jtwor 感谢回答,您是说 wx.cloud.callFunction()也是异步吗?
    lithium148
        10
    lithium148  
    OP
       2020-09-02 14:25:55 +08:00
    @chenluo0429 感谢回答,不是很明白您的意思。
    最后还是解决了,写成
    new Promise(function (resolve) {
    app.onLogin(resolve);
    }).then(()=>this.onGetDefaultTime())
    lithium148
        11
    lithium148  
    OP
       2020-09-02 14:28:40 +08:00
    @zhlssg 感谢回答,您是说这样吗 new Promise(function (resolve) {
    app.onLogin(resolve);
    }).then(()=>this.onGetDefaultTime())
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2920 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 14:38 · PVG 22:38 · LAX 07:38 · JFK 10:38
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.