23t*_*tux 9 javascript promise angularjs angular-promise
我想链接一些由服务返回的promise.只要一些返回promise的方法不需要额外的参数,这就可以工作.这是我的例子:
var first = function() {
var d = $q.defer();
$timeout(function() {
d.resolve("first resolved")
}, 100)
return d.promise;
};
var second = function(val) {
console.log("value of val: ", val);
var d = $q.defer();
$timeout(function() {
d.resolve("second resolved")
}, 200)
return d.promise;
};
first().then(second).then(function(value) {
console.log("all resolved", value);
});
Run Code Online (Sandbox Code Playgroud)
这按预期工作.但是,如果我的服务second
需要一个额外的参数val
来完成它的工作呢?随着价值之上的方法val
就是"first resolved"
,因为它得到的解析值的first
.
有没有办法,没有嵌套这样的匿名函数:
first().then(function() {
return second("foobar").then(function(value) {
console.log("all resolved", value);
});
});
Run Code Online (Sandbox Code Playgroud)
我正在考虑使用$q.all
,但恕我直言,你不能指定你的承诺的订单.
Raz*_*zem 10
当然.第一种方式:
first()
.then(function() {
return second("foobar");
})
.then(function(value) {
console.log("all resolved", value);
});
Run Code Online (Sandbox Code Playgroud)
第二种(更容易)方式:
first()
.then(second.bind(null, "foobar"))
.then(function(value) {
console.log("all resolved", value);
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4911 次 |
最近记录: |