加载上一个元素时加载所有元素



我有一个类似的元素的Map>

let list = [1,2,3,4,5,6]

我想加载一个项目,当前一个已经完成加载。

我知道如何使用一个,但不知道如何为列表中的所有元素连锁操作

let index = 0;
let complete = false;
httpcall(list[index]).subscribe(() => {
index++; 
httpcall(list[index]).subscribe(() => {
index++; 
httpcall(list[index]).subscribe(() => {
index++; 
httpcall(list[index]).subscribe(() => {  
index++; 
httpcall(list[index]).subscribe(() => {  
completer = true;
}
}
}
}
}

有更好的吗?

一旦您有了要迭代的所有项的数组,您就可以使用reduceRight创建每个回调,从末尾开始并向后工作,每次都将新创建的回调作为累加器传递,以便将每个subscribe调用链接到最后一个调用的末尾:

// Remove the first URL from the array,
// so that its `.subscribe` call can be used later to kick the process off
// once we've constructed the first callback for it:
const firstUrl = arr.shift();
const firstCallback = arr.reduceRight(
// Reduce callback:
(nextCallback, url) => () => {
httpcall(url).subscribe(nextCallback);
},
// Initial value for accumulator, that is, the first `nextCallback`:
() => {
completer = true;
// once this block is entered, everything is done
}
);
// Now that we've constructed the first callback,
// we can start the process for real with `firstUrl`:
httpcall(firstUrl).subscribe(firstCallback);

最新更新