关于如何使用异步方法(返回回调而不是回调)更优雅地实现此目的的任何想法吗?
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();
}
}
}
用法示例
webShare({
url: window.location.href,
noSupportCallback: this.handleCopyDesktop
});
答案 0 :(得分:0)
您可以返回被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());
}
}
用法:
webShare({
url: window.location.href,
}).catch(err => {
if (err instanceof NoSupportError) {
this.handleCopyDesktop();
} else {
console.error(err);
}
});