我有一系列ES6使能/承诺的情况。链中的第一个promise实际上是一个异步方法,它首先确定是否可以刷新缓存,然后链中的后续方法执行实际的刷新。
问题是,如果第一个方法确定我实际上不应该刷新缓存,我想要炸出链……我不需要做剩下的事。
我能够让它工作的唯一方法是将测试方法的结果和链中每个后续.then()的结果存储起来,测试是实际做什么还是返回一个简单的Promise.resolve(null)。
这看起来像是一堆额外的愚蠢的代码,实际上不应该出现在那里。
我下面的代码可以工作...错误处理正确...但是,有没有更好的方法来编写这种模式,在这种模式中,您只想有条件地继续使用链?一种不需要存储答案然后在every 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的承诺并不总是真正的承诺。因此,我最初的希望是,ES6 Promises的规范和实现能够满足这一看似重要的需求和用例。情况似乎并非如此。因此,其他问题的答案可能是这个问题的“正确”答案,但它们与ES6承诺无关。所以这对我来说似乎是不同的。
发布于 2016-07-29 12:17:31
但是,有没有更好的方法来编写这种模式,在这种模式中,您只想有条件地继续使用链?
您可以throw一个Error或使用.then()中的Promise.reject(),在.catch()上处理错误和处理错误消息或拒绝承诺原因
https://stackoverflow.com/questions/38650404
复制相似问题