How to output to console in real time in Javascript?

后端 未结 5 959
南方客
南方客 2020-12-20 09:40

In Javascript, when you write a piece of code like the one below, it seems like the computer will first complete the entire loop 100 000 times (which can take a second or tw

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-20 10:06

    One could feed an array of Promises to an Observable in order to achieve the desired outcome. Promises are now native to JavaScript and you can get the Observable from the RxJS library.

    Here is an example:

    const array = [];
    
    // This could also be a for of loop or a .map() function
    for (let i = 0; i <= 25; i++) {
      const promise = new Promise((resolve) => {
    
        // This could be any synchronous or asynchronous code
        setTimeout(() => {
          resolve(i);
        }, 1000 * i);
      });
    
      array.push(promise);
    }
    
    var observable = Rx.Observable.from(array);
    
    observable.subscribe((promise) => {
      promise.then(result => console.log(result));
    });

提交回复
热议问题