Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Promise.all() with Typescript

Tags:

typescript

Here is what I want to do:

Promise.all([aurelia.start(), entityManagerProvider.initialize()])     .then((results:Array<any>) => {         let aurelia: any = results[0];         aurelia.setRoot();     }); 

aurelia.start() returns an Aurelia type, while initialize() returns void.

The compiler gives an error message that the type cannot be inferred from the usage.

What I am trying to achieve is to get them to run at the same time, as they are both very long processes, then run Aurelia.setRoot();

like image 500
Greg Gum Avatar asked Nov 13 '15 01:11

Greg Gum


People also ask

Can we use promise in TypeScript?

Introduction to TypeScript promise. The promise in TypeScript is used to make asynchronous programming. The promise can be used when we want to handle multiple tasks at the same time. By the use of TypeScript promise, we can skip the current operation and move to the next line of the code.

Can I use promise all?

all() The Promise. all() method takes an iterable of promises as an input, and returns a single Promise that resolves to an array of the results of the input promises. This returned promise will fulfill when all of the input's promises have fulfilled, or if the input iterable contains no promises.

Can you await a promise all?

Any async promise-based function can have await in front of it to stop your code on that line until the promise is fulfilled, then return the result. Any function that returns a Promise, including web API calls, can be called using await.


1 Answers

Its generally best to have arrays with consistent types. You can do the following manually though (passing in generic arguments):

Promise.all<Aurelia, void>(   [aurelia.start(), entityManagerProvider.initialize() ]) .then(results => {     let aurelia = results[0];     aurelia.setRoot(); }); 
like image 141
basarat Avatar answered Sep 28 '22 03:09

basarat