Sequential code execution in angular/ typescript

后端 未结 7 2158
醉梦人生
醉梦人生 2021-01-01 06:02

How can I make my code run sequentially? For example,

  1. If I have a for loop which gets some data from a service, I want the n+1 iteration to run

7条回答
  •  伪装坚强ぢ
    2021-01-01 06:25

    Promise based solution:

    Promise.all() takes an array of promises and fires them all at the same time. Then once all of the promises resolve it will run the callback.

    let dataService = {
      get: function(i) {
        return new Promise((resolve, reject) => {
          setTimeout(resolve, 100, i);
        });
      }
    }
    
    let promises = [];
    
    for (var i = 0; i < 3; i++) {
        // get some data
        promises.push(dataService.get(i));
    }
    
    Promise.all(promises).then(values => { 
      console.log ('print me only after all iterations');
      console.log(values); 
    });
    

    Working sample: http://jsbin.com/ruqiwoxono/edit?js,console

    Promise.all docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

    Rxjs based solution:

    forkJoin basically does the same thing as Promise.all() but for observables

    let dataService = {
      get: function(i) {
        return Rx.Observable.of(i);
      }
    }
    
    let observables = [];
    
    for (var i = 0; i < 3; i++) {
        // get some data
        observables.push(dataService.get(i));
    }
    
    
    const example = Rx.Observable.forkJoin(observables);
    
    
    const subscribe = example.subscribe(values => {
      console.log ('print me only after all iterations');
      console.log(values); 
    });
    

    Working sample: http://jsbin.com/jolotuyoxa/edit?js,console

    Rxjs forkjoin docs: https://www.learnrxjs.io/operators/combination/forkjoin.html

提交回复
热议问题