使用此代码,我可以正确地添加到"MaterialCollectionSet">
let MaterialCollectionSet: Set<string> = new Set();
for(let data of SDE_REACTIONDATA) {
this.ESI.ReturnsType_AtId(data.materialTypeID).subscribe((MaterialData) => {
MaterialCollectionSet.add(MaterialData.name);
});
但是,尝试运行此代码
let MaterialCollectionSet: Set<string> = new Set();
for(let data of SDE_REACTIONDATA) {
this.ESI.ReturnsType_AtId(data.materialTypeID).subscribe((MaterialData) => {
MaterialCollectionSet.add(MaterialData.name);
});
console.log(MaterialCollectionSet);
将记录一个空集。
我知道这是由于在控制台.log在for-of 循环之外调用后发生的异步调用。
我的问题是,一旦 for-of 循环完成填充,如何实际使用 Set?
我们可以使用forkJoin
来等待所有请求
const requests$ = SDE_REACTIONDATA.map(data => this.ESI.ReturnsType_AtId(data.materialTypeID));
let MaterialCollectionSet: Set<string> = new Set();
forkJoin(requests$).subscribe(responses => {
// Now you can access the `responses`;
MaterialCollectionSet.add(responses.map(MaterialData => MaterialData.name));
})
或者正如@JB尼泽所建议的那样:
const requests$ = SDE_REACTIONDATA.map(data => this.ESI.ReturnsType_AtId(data.materialTypeID));
let MaterialCollectionSet: Set<string> = new Set();
merge(requests$).subscribe(
MaterialData => MaterialCollectionSet.add(MaterialData.name),
null, // error handler
() => console.log(MaterialCollectionSet) // complete
)
解决方案取决于您需要什么。