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

时间:2018-11-22 06:09:31

标签: javascript angular rxjs

我有一个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;
                }
            }
        }
    }
}

还有更好的东西吗?

1 个答案:

答案 0 :(得分:0)

一旦有了要迭代的所有项目的数组,就可以使用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);