0๐
โ
No, then
has two parameters so you would need to create two functions:
function successCallback(commit, name) {
return response => {
commit(name, response)
return Promise.resolve(response);
};
}
function failureCallback(commit, name) {
return error => {
commit(name)
return Promise.reject(error);
};
}
Then call them like
login({ commit }, user) {
return AuthService.login(user).then(successCallback(commit, 'loginSuccess'), failureCallback(commit, 'loginFailure'));
},
register({ commit }, user) {
return AuthService.register(user).then(successCallback(commit, 'registerSuccess'), failureCallback(commit, 'registerFailure'));
}
To make a single helper, you should either wrap the whole then
callback
function handle(commit, name, promise) {
return promise.then(successCallback(commit, name+'Success'), failureCallback(commit, name+'Failure');
}
login({ commit }, user) {
return handle(commit, 'login', AuthService.login(user));
},
register({ commit }, user) {
return handle(commit, 'register', AuthService.register(user));
}
or use spread syntax in the call, and return a tuple from the helper:
function handleCallbacks(commit, name) {
return [successCallback(commit, name+'Success'), failureCallback(commit, name+'Failure')];
}
login({ commit }, user) {
return AuthService.login(user).then(...handleCallbacks(commit, 'login'));
},
register({ commit }, user) {
return AuthService.register(user).then(...handleCallbacks(commit, 'register'));
}
Source:stackexchange.com