我们很难弄清楚如何使用已转换的ES6代码在链式承诺中处理上下文(或具体{commit}。下面是使用RxJS进行身份验证然后subscribes
的Login操作的一个示例用户作为流。我们需要在整个过程中提交几个突变,但不断出现commit is not a function
错误。
有没有人知道或有这样的事情的例子,或者任何人都可以提供关于在这种情况下处理上下文/提交的位置和方式的任何基本指导 - 例如什么时候可以使用ES6而不是,和/或上下文在哪里被提升(如果有的话),或者是否有更简单的方法来解决所有这些问题,比如将所有内容包装在主承诺中?由于我们需要在promise链中的每一步都提交,我们无法看到其中的一些如何工作:
const actions = {
login ({commit}, creds) { // need to commit here
commit('toggleLoading')
api.authenticate({
strategy: 'local',
...creds
})
.then(function (result) {
return api.passport.verifyJWT(result.accessToken)
})
.then(function ({commit}, payload) { //need to commit here
console.log(commit)
return api.service('users').get(payload.userId)
.subscribe(commit('setUser', user)) // need to commit here - but commit is not a function error
})
.catch(function ({commit}, error) {
commit('setErr', `ERROR AUTHENTICATING: {$err.message}`) // need to commit here but commit is not a function error
commit('toggleLoading')
})
}
我们发现的所有示例都是简单化的,并且每个操作只显示一个提交(或者可能包含2个if)。任何帮助或反馈都表示赞赏!
答案 0 :(得分:1)
首先,.then
和.catch
中的回调函数只接受一个参数,你已经编码了两个...但是,来自commit
参数的login
仍在范围内,因此修复起来非常简单
您的代码可以简化如下
const actions = {
login ({commit}, creds) {
commit('toggleLoading');
api.authenticate({strategy: 'local', ...creds})
.then(result => api.passport.verifyJWT(result.accessToken))
.then(payload => api.service('users').get(payload.userId).subscribe(commit('setUser', user)))
.catch(function (error) {
commit('setErr', `ERROR AUTHENTICATING: ${error.message}`);
commit('toggleLoading');
});
}
注意:{$err.message}
中有.catch
,而我应该${error.message}