107

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();

12 Answers 12

94

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();
});
4
  • 1
    Visual Studio Code approves that syntax but the tslint bundled in my build system complains: the array is not declared correctly it should be Type[] or Array<Type>. Strangely, searching for that error message yields exactly 0 results. Aug 8, 2016 at 13:41
  • 1
    so write let foo : Array<Promise<Aurelia>,Promise<void>> = [aurelia.start(), entityManagerProvider.initialize()];
    – noam aghai
    Oct 5, 2017 at 18:33
  • 5
    Looks like this is working for me with pure inference now. It returns a type of Promise<[T1,T2]> which works great. I'm not sure if this is due to recent compiler features or just that the typings for ES6 promises are now better than they used to be. At any rate, the inference here is impressive. Oct 13, 2017 at 20:16
  • 4
    -1: Typing via Promise.all<T, Y, Z, number, ...> is more straightforward than declaring a typed array of promises first. See the answer: stackoverflow.com/a/40430386/457268
    – k0pernikus
    Nov 6, 2017 at 16:22
69

Since Promise::all is a generic function, you can declare the return types of each promise like this:

Promise.all<Aurelia, void>([
  aurelia.start(),
  entityManagerProvider.initialize()
])
.then(([aurelia]) => aurelia.setRoot());
4
  • 1
    in vscode it works perfectly. but somehow when i compile it via tsc it says error TS2346: Supplied parameters do not match any signature of call target. (tsc -v 2.0.6). Any solutions?
    – DevTrong
    Nov 16, 2016 at 11:54
  • This yields "Supplied parameters do not match any signature of call target." in 2.1.4 as well.
    – John Weisz
    Dec 22, 2016 at 16:26
  • 4
    In Typescript 2.7.2, I'm finding that it is able to correctly infer the types in the array passed into the then() block without even having to declare the types 'ahead of time' as generic parameters upon Promise::all. Mar 14, 2018 at 13:03
  • @JamieBirch thanks, it seems to work on 2.7.1 as well.
    – joonas.fi
    Apr 21, 2018 at 16:29
30

At least from TypeScript 2.7.1 onwards, the compiler seems to resolve the types without help, with a syntax like this:

Promise.all([fooPromise, barPromise]).then(([foo, bar]) => {
  // compiler correctly warns if someField not found from foo's type
  console.log(foo.someField);
});

Hat tip: @JamieBirch (from comment to @AndrewKirkegaard's answer)

1
  • 7
    Or better yet const results: [foo, bar] = await Promise.all([fooPromise, barPromise]); to update this slightly
    – Liam
    Apr 30, 2021 at 15:55
11

If you'd like to keep type-safety, it's possible to extend the native type-definition of the Promise object (of type PromiseConstructor) with additional overload signatures for when Promise.all is called with a finite number of not-necessarily inter-assignable values:

interface PromiseConstructor
{
    all<T1, T2>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>]): Promise<[T1, T2]>;
    all<T1, T2, T3>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>]): Promise<[T1, T2, T3]>;
    ...
}

Add as many overloads as you need. This approach provides full type-safety for all elements in the value argument of the onfulfilled callback:

Promise.all([1, "string", true]).then(value =>
{
    let a: number = value[0]; // OK
    let b: number = value[1]; // Type 'string' is not assignable to type 'number'.
    ...
});
3
  • 2
    I think that is an elegant solution.
    – Greg Gum
    Dec 22, 2016 at 23:31
  • Doesn't scale very well when you don't know how many you will have in advance
    – blockhead
    Jul 11, 2017 at 4:43
  • @blockhead If you need more than about 3-5 you are better off restructuring to receive a single object anyways. This is precisely for the cases where you only have some values to consider.
    – John Weisz
    Jul 11, 2017 at 9:24
3

PART 1

There are functions you need to understand A) Promise.all and B) Promise.then:

A) the type definition of Promise.all is a function:

    all<T>(values: readonly (T | PromiseLike<T>)[]): Promise<T[]>;

B) the type definition of Promise.then is a function that is a bit more complex:

    then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): Promise<TResult1 | TResult2>;

PART 1.a

Promise.then's type definition is a lot but it can be broken down into small parts:

then<TResult1 = T, TResult2 = never> a function then with 2 generics TResult1, TResult2. The < > means we can set and use values inside them later - they are called generics.

The then function itself: (onfulfilled?: ..., onrejected?: ...): Promise<TResult1 | TResult2>.

PromiseLike is a helper type and the same as Promise (for an intro lesson).

onfulfiled and onrejected are functions in the form of: (value: T) => (TResult1 OR PromiseLike<TResult1>) OR undefined OR null. Notice the generic T is used here.

PART 2 -

Promise itself has a generic interface: interface Promise<T>. The <T> is a/the generic.

So when you call

Promise.all<SomeCoolType>([a(), b(), c()]).then( value => doSomething(value) )

your generic is SomeCoolType and in this example some cool type is

interface SomeCoolType = [A() => string, B() => boolean, C() => number]

Now remember that A B C have to be Promises. And this makes it so your value in .then( value => ... is going to the result of SomeCoolType which for us is calling all those functions, the result is [string, boolean, number].

CONCLUSION -

Concretely, the array of function/promises you pass into you Promise.all<T> are generics that are used in .then(result => ...). The return/resolve value of those promises will become the value/type of result.

Example: Promise.all<[Promise<() => string>]>([returnStringAsync()]).then(result => console.log(typeof result === "string")); # => true

3

A full example:

type returnString = string;
type returnNumberType = number;
type jobsType = [Promise<returnString>, Promise<returnNumberType>];

const returnString = async (): Promise<returnString> => {
  return 'This is a string';
};

const returnNumber = async (): Promise<returnNumberType> => {
  return 123;
};

const jobs = [];

jobs.push(returnString());

if (Math.random() > 0.5) {
  jobs.push(returnNumber());
}

(async () => {
  const results = await Promise.all(jobs as jobsType);
  // results now has the correct.
  // tslint:disable-next-line: no-console
  console.log(results);
})();

2

For anyone looking for a way to use Promise.all in React TypeScript:

Promise.all<Foo, Bar>(fooPromise, barPromise)

where fooPromise and barPromise are the promises you want to execute in parallel, fooPromise returns a foo type response, and barPromise returns a bar type response.

If you check the response at .then, you'll see the response is a tuple: [Foo, Bar].

1

When using promises that return values, my favorite using of Promise.all() is using array destructuring as below. Using await is more readable and destructuring is filling up the right variables.

export interface IDeveVersionHubDataService {
    getBuildFilterDeveVersions(): Promise<IBuildFilterDeveVersionDto[]>;
    getBuildFilterUsers(): Promise<IBuildFilterUserDto[]>;
}
const loadDeveVersions = deveVersionHubDataService.getBuildFilterDeveVersions();
const loadUsers = deveVersionHubDataService.getBuildFilterUsers();

const [deveVersions, users] = await Promise.all([loadDeveVersions, loadUsers]);     
0

I somehow landed here when I was looking for return type of Promise.all() since straightforward [Promise<any>, Promise<any>] is obviously not working.

Eventually it turned out to be simplier than it seems:

const severalMongoDbOperations: Promise<[DeleteWriteOpResultObject, UpdateWriteOpResult]> =
  () => Promise.all([
    mongo.deleteOne({ ... }),
    mongo.updateOne({ ... })
  ]);

Later it can be used with .then() or:

try {
  const ops: [DeleteWriteOpResultObject, UpdateWriteOpResult] = await severalMongoDbOperations();
} catch (e) {
  // Process rejection
}
0

I have the same issue with you, but with this code, all work perfectly.

type TList = Promise<Aurelia> | Promise<void>;

const foo: TList[] = [aurelia.start(), entityManagerProvider.initialize()];

Promise.all<TList>(foo).then((results) => {
    let aurelia = results[0];
    aurelia.setRoot();
});
0

Promise.all returns "a single Promise that resolves to an array of the results of the input promises" (from MDN).

You can get the results of all the promises if you await the promise all.

        const [tomorrow, today, yesterday] = await Promise.all([
            fun('tomorrow'),
            fun('today'),
            fun('yesterday')
        ]);
2
  • 1
    No: Promise.all returns "a single Promise that resolves to an array of the results of the input promises" (from MDN). Also, this question was about TypeScript and the type inference with different input promise types.
    – boycy
    Apr 5, 2022 at 16:33
  • @boycy thanks for pointing out the error in my wording. I changed my post. Apr 27, 2022 at 22:19
0

In this example OrderHistoryParser.parseOrders() returns Order[] type and StorageUtils.getLocalProperty generic:

return Promise.all([OrderHistoryParser.parseOrders(), StorageUtils.getLocalProperty(StorageProperties.SESSION_PARSE_RESULT) as Promise<ParseResults>])
      .then(([parsedOrders, sessionParsedResult]) => {
        here 
        parsedOrders would be Order[]
        sessionParsedResult would be ParseResults

      })

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.