Search code examples
node.jspromise

Promise all to map or object


I have some sequalize promises.

 private loadFilterMetaData(): Array<Promise<any>> {
        const country = CatalogCountry.findAll();    
        const firm = CatalogFirm.findAll();    
        const promises = [country, firm];    
        return promises;
     }

And i want to save resuts from that promises as key-based structure ,assoc array or map.

Is there any another ways to do that without helper array of names and foreach counter variables?

      this.metaDataInjectableFilters=['country','firm'];   
            const metaData = await Promise.all(metaDataPromises);
        
            let i = 0;
            metaData.forEach(resolved => {                                  
            this.metaData.set(
              this.metaDataInjectableFilters[i], 
              resolved
            );
            i++;
            })

Solution

  • As a variant you can define your promises within an object. Then, use Object.values() in combination with Promise.all() to resolve these promises. Finally, reduce() by the keys of the original promises object to associate the resolved values:

    const promises = {
        country: CatalogCountry.findAll(),
        firm: CatalogFirm.findAll(),
    };
    
    const results = await Promise.all(Object.values(promises));
    
    const metaData = Object.keys(promises).reduce((acc, key, index) => {
        acc[key] = results[index];
        return acc;
    }, {});