onShareAppMessage 处理多个顺序异步请求能且只能执行一个
发布于 7 年前 作者 yan84 17304 次浏览 来自 问答
onShareAppMessage() {
    // 生成带场景值的小程序码
    entry.generationMiniProgramCode(path, JSON.stringify(param), result => {
      let o = {
        title: 'VIP微课,音乐人的在线大学',
        // path: path + '?scene=' + result.scene,
        success(res) {
          console.log('分享success')
          console.log(res)
          // 记录用户分享行为
          entry.postUserShare(path, result.scene, shareResult => {
            wx.showToast({
              title: '分享成功',
              icon: 'none',
            })
          })
        },
        fail(res) {
          console.log('fail')
        }
      }
      return o
    })
  }
2 回复

onShareAppMessage 是要求立即返回一个对象的,不会等待 Promise 的结果。建议你提前把结果存起来,在这个函数直接 return。onShareAppMessage 的函数签名是


(options?: {from: string, options?: any}) => {title?: string, path?: string, imageUrl?: string} | undefined


而你写的这个函数的签名是


() => Promise<{title: string, success: Function, fail: Function}>


显然是不一样的。

return 后的数据需要另一个异步请求获取,现在情况是一旦onShareAppMessage触发就执行其上一层异步回调。

onShareAppMessage() {
    // 生成带场景值的小程序码
    let path = '/pages/index/index'
    let userId = wx.getStorageSync('USERID');
    let param = {
      "userId": userId
    }
    let a = new Promise((res, rej) => {
      entry.generationMiniProgramCode(path, JSON.stringify(param), result => {
        path = path + '?scene=' + result.scene
        return res(path)
      })
    })
    a.then(path => {
      console.log(path)
      return {
        title: 'VIP微课,音乐人的在线大学',
        // path: path + '?scene=' + result.scene,
        success(res) {
          console.log('分享success')
          console.log(res)
          // 记录用户分享行为
          entry.postUserShare(path, 1213, shareResult => {
            wx.showToast({
              title: '分享成功',
              icon: 'none',
            })
          })
        },
        fail(res) {
          console.log('fail')
        }
      }
    })

换成promise的方式也不行。

回到顶部