把承诺放在一起
Putting Togther Q Promises
我正在学习 JS promises 并且在理解事物方面取得了一些进步,但是不确定如何将它与 return
结合起来并使用 Q.all
假设我有一个函数:(getParentsForLocation
return是一个承诺)
function doBusiness() {
return Q.all(
locations.map(function(item, currentIndex) {
return getParentsForLocation(item.id)
.then(function(res) {
return checkParent(res, currentIndex)
}
});
}))
.then(_.uniq(locations))
}
然后按照这个,即在该映射遍历 locations
数组中的所有元素之后,我想 运行 类似于下划线的 uniq
函数:_.uniq(someArrayIHave);
- 我需要将它放在
Q.all([])
中吗? \
- 如果是这样,它会按顺序 运行 该数组中的每个方法吗?
- 我想我需要用那个
doBusiness()
函数做一些事情,例如return 一些承诺,但不确定它看起来如何?
感谢任何帮助。
非常感谢。
Do i need to place this in a Q.all(…)
?
是的。您的 map()
电话应该会给您带来一系列承诺。
If so, would it run each method in that array sequentially?
没有。或者至少,我们不知道,他们可以在内部做任何事情。
I presume there is something I'd need to do with that doBusiness()
function, e.g. return some promise
是的。来自我的promise rules of thumb:如果一个函数做一些异步的事情,它必须return一个承诺。你的两个回调函数也是如此。
How would that look?
function doBusiness() {
return Q.all(locations.map(function(item, currentIndex) {
// ^^^^^^ ^^^^^^
return getParentsForLocation(item.id)
// ^^^^^^
.then(function(res) {
return updateDB(res, currentIndex);
// ^^^^^^
});
}));
// ^
}
我正在学习 JS promises 并且在理解事物方面取得了一些进步,但是不确定如何将它与 return
结合起来并使用 Q.all
假设我有一个函数:(getParentsForLocation
return是一个承诺)
function doBusiness() {
return Q.all(
locations.map(function(item, currentIndex) {
return getParentsForLocation(item.id)
.then(function(res) {
return checkParent(res, currentIndex)
}
});
}))
.then(_.uniq(locations))
}
然后按照这个,即在该映射遍历 locations
数组中的所有元素之后,我想 运行 类似于下划线的 uniq
函数:_.uniq(someArrayIHave);
- 我需要将它放在
Q.all([])
中吗? \ - 如果是这样,它会按顺序 运行 该数组中的每个方法吗?
- 我想我需要用那个
doBusiness()
函数做一些事情,例如return 一些承诺,但不确定它看起来如何?
感谢任何帮助。
非常感谢。
Do i need to place this in a
Q.all(…)
?
是的。您的 map()
电话应该会给您带来一系列承诺。
If so, would it run each method in that array sequentially?
没有。或者至少,我们不知道,他们可以在内部做任何事情。
I presume there is something I'd need to do with that
doBusiness()
function, e.g. return some promise
是的。来自我的promise rules of thumb:如果一个函数做一些异步的事情,它必须return一个承诺。你的两个回调函数也是如此。
How would that look?
function doBusiness() {
return Q.all(locations.map(function(item, currentIndex) {
// ^^^^^^ ^^^^^^
return getParentsForLocation(item.id)
// ^^^^^^
.then(function(res) {
return updateDB(res, currentIndex);
// ^^^^^^
});
}));
// ^
}