我有一个调用另一个函数 moreFoo 的函数 foo,我想将函数调用包装在 promise 中,以便 foo 返回的 promise > 在 moreFoo 解决后返回。这是我的解决方案:
function foo() {
var defer = $q.defer();
console.log('doing foo');
moreFoo().then(defer.resolve);
return defer.promise;
}
function moreFoo() {
var defer = $q.defer();
setTimeout(function() {
console.log('doing more foo');
defer.resolve();
}, 2000);
return defer.promise;
}
foo().then(function() {
console.log('finished with all foos');
});
然后输出:
doing foo doing more foo finished with all foos
它似乎按预期工作。这是链接这些 promise 的正确/最佳方式吗?
最佳答案
我不知道“最佳”是什么,但这可以通过利用 $timeout
它返回的 promise 来简化很多......
function foo() {
console.log('doing foo');
return moreFoo();
}
function moreFoo() {
return $timeout(function() {
console.log('doing more foo');
}, 2000);
}
foo().then(function() {
console.log('finished with all foos');
});
关于javascript - Angular : Is this the correct way to chain promises?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24770121/