Any ideas on how to implement this more elegantly using async that returns a promise instead of callbacks?
const webShare = (data) => {
if (navigator.share) {
navigator.share({
title: data.title,
text: data.text,
url: data.url
}).then(() => {
if (typeof data.successCallback === 'function') {
data.successCallback();
}
}).catch(console.error);
} else {
if (typeof data.noSupportCallback === 'function') {
data.noSupportCallback();
}
}
}
Usage example
webShare({
url: window.location.href,
noSupportCallback: this.handleCopyDesktop
});
You could return a promise that gets rejected with a NoSupportError
:
class NoSupportError extends Error {}
const webShare = (data) => {
if (navigator.share) {
return navigator.share({
title: data.title,
text: data.text,
url: data.url
})
} else {
return Promise.reject(new NoSupportError());
}
}
Usage:
webShare({
url: window.location.href,
}).catch(err => {
if (err instanceof NoSupportError) {
this.handleCopyDesktop();
} else {
console.error(err);
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.