Xen*_*Sis 2 javascript promise rxjs
我遇到一种奇怪的情况,在收到Rx Promise的结果并进行了一些检查之后,我想中断for循环。我有以下内容:
function getDrift(groups) {
var drift = {};
groups.forEach(function(group) {
if(group.type === 'something') {
for(var i = 0; i < group.entries.length; i++) {
fetchEntry(group.entries[i].id)
.then(function(entry) {
if(entry.type === 'someType'){
drift[entry._id] = getCoordinates(entry);
// break;
}
});
}
}
});
return drift;
}
Run Code Online (Sandbox Code Playgroud)
在哪里fetchEntry基于ID返回mongodb文档的Promise。如果if检查满意,我想中断当前循环group.entries并继续进行下一组。
那可能吗?
谢谢
编辑:根据要求,组对象看起来像这样:
[
{
type: 'writing',
entries: [{id: "someId", name: "someName"}, {id: "someId2", name: "someName2"}]
},
{
type: 'reading',
entries: [{id: "someId3", name: "someName3"}, {id: "someId4", name: "someName4"}]
}
]
Run Code Online (Sandbox Code Playgroud)
解决方案:我最终将@MikeC的建议与递归和回调一起使用以返回所需的值。谢谢你们!
这是不可能的,因为Promises是异步的,这意味着then直到所有其他同步代码完成才执行。
如果您不想基于某种条件处理所有这些函数,我建议您创建一个函数,如果要继续执行该函数。
(function process(index) {
if (index >= group.entries.length) {
return;
}
fetchEntry(group.entries[index])
.then(function(entry) {
if(entry.type === 'someType'){
drift[entry._id] = getCoordinates(entry);
// don't call the function again
} else {
process(index + 1);
}
});
})(0);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6543 次 |
| 最近记录: |