有没有一种更优雅、更直观的方式来打破ES6 Promise链

Is there a more elegant and intuitive way to break out of an ES6 Promise chain?

本文关键字:方式 Promise ES6 直观 一种 有没有      更新时间:2023-09-26

我有一个ES6 thenables/promise链的情况。链中的第一个promise实际上是一个异步方法,它首先确定是否可以刷新缓存,然后由链中的后续方法进行实际刷新。

问题是,如果第一个方法确定我实际上不应该刷新缓存,我想炸出链。。。。我不需要做剩下的。

我能做到这一点的唯一方法是存储测试方法的结果和链中每个后续.then()的结果,以测试是否真的要做某事或返回一个简单的Promise.resolve(null).

这看起来像是一堆额外的愚蠢代码,不应该真的存在。

我下面的代码有效。。。。错误处理是正确的。。。。但是,有没有更好的方法来编码这种模式,即只想有条件地继续使用链?一种不需要存储答案,然后在每个then()上强制执行Promise.resolve()的方法?

function asyncRefreshCache(wDb, forceRefresh) {
    var cachedDataVersions;
    var allowRefresh;
    return wDb.asyncCacheRefreshAllowed(forceRefresh) // Here I test whether I am allowed to really refresh the cache.
        .then(function (ar) {
            allowRefresh = ar;
            return allowRefresh 
                ? wDb.asyncGetCacheDataVersionsForRefresh() // Only do this if allowed above.
                : Promise.resolve(null); //Yuck.  Would love to just break out.  But how?
        })
        .then(function (dataVersions) {
            cachedDataVersions = dataVersions;
            return allowRefresh
                ? asyncServerFlexSearch({ dataVersions: dataVersions, includeInactiveFlag: true, onLoadFlag: true }) // Only do this if allowed above.
                : Promise.resolve(null); //Yuck.  Would love to just break out.  But how?
        })
        .then(function (serverResponse) {
            return allowRefresh
                ? wDb.asyncMergeCleanDataFromServerToCache(cachedDataVersions, serverResponse) // Only do this if allowed above.
                : Promise.resolve(null); //Yuck.  Would love to just break out.  But how?
        });
}

编辑:由于Q Promises和JQuery Promises的问题相似,此问题被标记为重复。JQuery Promises并不是真正的承诺。因此,我最初的希望是ES6-Promises的规范和实现能够满足这个看似重要的需求和用例。看来情况可能并非如此。因此,其他问题的答案可能是这个问题的"正确"答案,但它们与ES6承诺无关。所以这对我来说似乎不一样。

但是有没有更好的方法来编码这种模式想有条件地继续使用链吗?

您可以从Errorthrow或使用.then()中的Promise.reject(),在.catch() 中处理错误和处理错误消息或拒绝承诺原因