【问题标题】:Promises, argument in .then() is undefined, how to pass?Promises,.then() 中的参数未定义,如何通过?
【发布时间】:2018-07-05 04:11:31
【问题描述】:

我正在使用this 指南在 Promise 中运行一些父函数。这是一个 React 示例,我使用的是 Vue.js。

我的问题是,即使我完全按照示例构建 Promise,我仍然遇到 actions undefined 问题。

即参数 actions 没有在 thenable (.then()) 方法中定义。

我知道.then() 创建了一个新对象,我应该明确地将参数传递给该对象。这会产生 2 个问题:

1) 示例中的 actions 参数是如何定义在 .then() 中的。 是因为 Vue 和 React 的不同吗?

2) 由于connect() 隐式解析为user 对象,我如何将额外变量(在我的情况下为actions 参数)绑定或添加到解析方法。

这是我的单例代码:

var chatKitConnectionSingleton = (function () {
  var instance;

  function init({ state, actions }, uid) {

    new ChatManager({
      instanceLocator: "##:###:###-###-###-###",
      userId: uid,
      tokenProvider: new TokenProvider({url: '...' })
    })
      .connect({
      onAddedToRoom: room => {
        actions.selectRoomAsCurrent(room)
      },
      onRemovedFromRoom: room => {
        actions.removeRoomLocally(room.id)
      },
      onRoomDeleted: room => {
        actions.removeRoomLocally(room.id)
      }
    })
      .then(user => {
      actions.setCurrentUser(user)
      Promise.all(
        user.rooms.map(room =>
                       user.subscribeToRoom({
          roomId: room.id,
          hooks: {
            onNewMessage: message => {
              actions.newMessageArrived(message)
            }
          },
          messageLimit: 10
        })
                      )
      ).then(rooms => {
        actions.setRoomsFromChatkit(rooms)

      }).catch(err =>{
        actions.setRoomsFromChatkit([])
      })
    })
      .catch(error => console.log('CHATKIT | Error on connection', error))
  };

  return {

    getInstance: function ({ state, actions },uid) {
      if ( !instance ) {
        instance = init({ state, actions },uid);
      }
      return instance;
    }
  };
})();

编辑

我刚刚发现 actions 参数在连接钩子中也未定义:|

我想真正的问题是,如何将 Vue 组件 methods 传递给单例。

目前,我正在这样做,但它解析为actions undefined。

  let chatManagerConnectPromise = chatConnection(this, uid)

意思是 this 不会像 React 中那样解析为 {state, actions}。有谁知道如何在 Vue 中做到这一点?

非常感谢!

【问题讨论】:

  • 谢谢,但没用。即使在 return Promise.all( 之前以及在 Promise 内部,actions 也是未定义的,即使您建议的编辑也是如此。
  • 你能把这个函数 init({ state, actions }, uid) { -> 改成 ({state, actions}, uid) => {}

标签: javascript vue.js ecmascript-6 promise


【解决方案1】:

actions 超出了函数范围。需要手动绑定或者使用 ES6 箭头函数来避免 undefined。

【讨论】:

    【解决方案2】:

    好吧,这是我想太多问题了。

    在 Vue 中,当将 this 传递给外部函数时,Vue 不会像 React 那样将其视为 {state, actions}

    参数(在我的例子中是this)的使用方式应该与在组件本身内部使用的方式相同。通过this.myMethod()调用方法

    我将参数从 {state, actions} 更改为 -> actions 一切正常。

    感谢指点!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-30
      • 1970-01-01
      • 2014-03-01
      • 1970-01-01
      相关资源
      最近更新 更多