Home > Blockchain >  Typescript Promise.all for Map
Typescript Promise.all for Map

Time:11-25

I want to do the following demonstrated with an Array with a Map:

export class Example {

    // No errors
    public withArray(): Promise<Item[]> {
        var promises: Promise<Item>[] = [];
        promises.push(Promise.resolve(Item));
        return Promise.all(promises);
    }

    // Issues with initialisation 
    public withMap(): Promise<Map<Item, Item>> {
        var promises: Promise<Map<Item, Item>> = new Map();
        promises.push(Promise.resolve([Item, Item]));
        return Promise.all(promises);
    }
}

It complains with the following error message:

Type 'Map<any, any>' is missing the following properties from type 'Promise<Map<Item, Item>>': then, catch, finally

My question would be, how do I define the type Map on the promises so that I can add [Key, Value] to a Map that will then get returned.

CodePudding user response:

TL;DR: var promises = Map<Item, Promise<Item>> = new Map().

An alternative way to write Promise<Item>[] would be Array<Promise<Item>>. Notice that both cases indicate the same: an Array of Promises that should resolve with Item. Array -> promises -> items.

In your second case, you are typing Promise<Map<Item, Item>>, which is a Promise -> Map -> items, instead of Map -> promises -> items. What you are looking for is a Map<Item, Promise<Item>>.

Also, there seem to be quite a few other issues with that code. Notice that Map does not have a push method.

  • Related