将带有回调的函数转换为异步Promise

时间:2020-02-24 23:19:36

标签: javascript asynchronous es6-promise

关于如何使用异步方法(返回回调而不是回调)更优雅地实现此目的的任何想法吗?

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
});

1 个答案:

答案 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);
    }
});