以下代码片段是否等价?
版本 1
function doSomething() {
var defer = $q.defer();
foo().then(function() {
bar().then(function() {
defer.resolve();
});
});
return defer.promise;
}
版本 2
function doSomething() {
return foo().then(bar);
}
最佳答案
这两种方法之间存在许多差异。
这两个片段之间的主要区别在于,在 version 2
中,您隐式地将解析后的值从 foo
直接传递给 bar
。
除此之外,doSomething
将解决任何 bar
将解决的问题,而在 version 1
中,结果将被丢弃。
Benjamin Gruenbaum 提出的一些其他重要观点:
(a) if bar is a reference error 1 rejects the inner promise and 2 throws.
(b) 1 requires a reference to $q where 2 is implementation agnostic.
(c) version 1 is not exception safe and a rejection will be swallowed where version 2 will let you .catch a rejection. ; There are several smaller differences as well. See stackoverflow.com/questions/22539815
你也可以这样写。
这样你就不会得到从 foo
到 bar
的解析值的隐式传递(现在是显式的),这可能会造成混淆或容易被忽视。如果您想在返回之前对 foo
或 bar
的解析值执行某些操作,它也很有用。
function doSomething() {
return foo().then(function(res){
// maybe do something with the result of foo
return bar(res);
}).then(function(res){
// maybe do something with the result of bar
return res;
});
}
应尽量减少手动创建延迟对象,这通常是一种反模式。
https://github.com/petkaantonov/bluebird/wiki/Promise-anti-patterns#the-deferred-anti-pattern
此处演示的关键原则是 promise 将在其 resolve 方法中采用返回的 promise (或 thenable )的状态。
关于javascript - 简化 Javascript 中的 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25014626/