【发布时间】:2019-09-06 09:58:57
【问题描述】:
我有一些接受现有承诺的 javasript 代码 (比如说,fetch() 返回的承诺)并增加价值 (比如说,then/catch listeners 进行调试,或者更多):
let myFetch = function(url) {
return fetch(url).then(function(value) {
console.log("fetch succeeded: value=",value);
return value;
}.catch(function(reason) {
console.log("fetch failed: reason=",reason);
throw reason;
});
};
我发现自己修改了上面的代码,以便仅在某些条件为真时才添加侦听器:
let myFetch = function(url) {
let promise = fetch(url);
if (some condition) {
promise = promise.then(function(value) {
console.log("fetch succeeded: value=",value);
return value;
}.catch(function(reason) {
console.log("fetch failed: reason=",reason);
throw reason;
});
}
return promise;
};
现在我想知道,myFetch 返回“then”返回的新承诺是否真的有意义 (实际上 catch 是另一个“then”的简写)如上, 还是返回原始承诺(带有添加的侦听器)更有意义? 换句话说,我正在考虑省略第二个“promise =”, 使代码看起来像这样:
let myFetch = function(url) {
let promise = fetch(url);
if (some condition) {
promise.then(function(value) {
console.log("fetch succeeded: value=",value);
return value;
}.catch(function(reason) {
console.log("fetch failed: reason=",reason);
throw reason;
});
}
return promise;
};
这与以前的版本有什么不同吗? 哪个版本更可取,如果是,为什么?
【问题讨论】:
-
Can I fire and forget a promise? 的可能重复项(使用 async/await,但问题相同)。
标签: javascript promise es6-promise