Reputation: 3158
I have the following code that determines if the browser is IE11 or not. It then resolves that promise by notifying that the password has been copied to the clipboad or failed to save.
But you will notice, that I am using the same code twice (the .then().catch() block are exactly the same). Anyway to condense this?
copyToClipBoard(str) {
if (this.isIE11()) {
this.copyToIE11ClipBoard(str)
.then(() => {
eventBus.$emit('addSnack', {
type: 'info',
text: i18n.t('copy'),
buttonText: i18n.t('ok'),
});
})
.catch(() => {
eventBus.$emit('addSnack', {
type: 'info',
text: i18n.t('copy-fail'),
buttonText: i18n.t('ok'),
});
});
} else {
navigator.clipboard
.writeText(str)
.then(() => {
eventBus.$emit('addSnack', {
type: 'info',
text: i18n.t('copy'),
buttonText: i18n.t('ok'),
});
})
.catch(() => {
eventBus.$emit('addSnack', {
type: 'info',
text: i18n.t('copy-fail'),
buttonText: i18n.t('ok'),
});
});
}
},
isIE11() {
return !!window.MSInputMethodContext && !!document.documentMode;
},
copyToIE11ClipBoard(str) {
return new Promise((resolve, reject) => {
const password = window.clipboardData.setData('Text', str);
if (password) {
resolve();
} else {
reject();
}
});
}
Upvotes: 0
Views: 33
Reputation: 1732
You can define two functions for the success case and failure case.
const successFunction= () => {
eventBus.$emit('addSnack', {
type: 'info',
text: i18n.t('copy'),
buttonText: i18n.t('ok'),
});
}
const failureFunction = () => {
eventBus.$emit('addSnack', {
type: 'info',
text: i18n.t('copy-fail'),
buttonText: i18n.t('ok'),
});
}
in your function,
this.copyToIE11ClipBoard(str).then(successFunction),catch(failureFunction);
Upvotes: 0
Reputation: 943185
The same way you reuse any value.
Store it in a variable.
const myThen = () => {
eventBus.$emit('addSnack', {
type: 'info',
text: i18n.t('copy'),
buttonText: i18n.t('ok'),
});
}
Then use the variable.
.writeText(str)
.then(myThen)
Better yet. Don't do all the calls to then
and catch
inside the if/else
branch.
Bring the promise out of the if/else
and have a shared chain of logic for the rest of the code.
At that point, your if/else
logic becomes "Get the value from one of two function calls depending on an expression" and you can move to a conditional operator.
copyToClipBoard(str) {
const promise = this.isIE11()
? this.copyToIE11ClipBoard(str)
: navigator.clipboard.writeText(str);
promise.then(() => {
eventBus.$emit('addSnack', {
// etc
Upvotes: 3