DEV Community

CodetoLive blog
CodetoLive blog

Posted on • Originally published at codetolive.in on

What is Promise.all() in Typescript?

The Promise.all() function accepts a collection of promises as input and returns an array of results when all of the provided Promises resolve, or rejected when any Promise is rejected. It is useful for aggregating all the promises and retrieving the results at the same time. It is typically useful when you want to load all the data at once before starting the desired functionality.

Promise.all() will reject any of the input promises immediately.

Code:

promiseall.component.ts:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-promiseall',
  templateUrl: './promiseall.component.html',
  styleUrls: ['./promiseall.component.css']
})

export class PromiseallComponent implements OnInit {

  approach1: any[] = [];
  approach2: any[] = [];

  ngOnInit(){
    debugger
    this.executePromiseApproach1();
    this.executePromiseApproach2();
  }

  getCustomerData(customerId: Number) {
    return new Promise<Number>((resolve, reject) => {
      resolve(customerId);
    });
  }

  executePromiseApproach1(){
    let customDataPromises:Promise<any>[] = [];

    customDataPromises.push(this.getCustomerData(1));
    customDataPromises.push(this.getCustomerData(2));
    customDataPromises.push(this.getCustomerData(3));

    return Promise.all(customDataPromises).then((result: any[]) => {
      console.log(result);
      this.approach1 = result;
    });
  }

  executePromiseApproach2(){
    const promise1 = new Promise((resolve, reject) => {
      setTimeout(resolve, 1000, 'sample');
    });

    const promise2 = Promise.resolve(1000);
    const promise3 = 500;

    Promise.all([promise1, promise2, promise3]).then((result) => {
      console.log(result);
      this.approach2 = result;
    });
  }
}

promiseall.component.html:
<p>
    Promise.all() approach 1: {{approach1}}  
</p>
<p>
    Promise.all() approach 2: {{approach2}}  
</p>

Enter fullscreen mode Exit fullscreen mode

Result:

  • Promise.all() approach 1: 1,2,3
  • Promise.all() approach 2: sample,1000,500

Download the above example source code from Github - Download

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay