I was assuming that by using await I am making sure that the promise will get completed(it will wait at this statement until the promise is complete) before moving to the execution of next line. But seems I am wrong. I tried reading about it and going through with a lot of examples but still I am unable to understand why it doesnt work. Somehow, I am trying to relate these promises and chaining of it with Java's CompletableFutures but not able to completely understand it.
Not sure what is wrong with the below code. "productDetailsMap" is always coming as empty when invoking "getProductDetailsAndEnrichFulfillmentGroupIds".
async getProductDetailsAndEnrichFulfillmentGroupIds(authHeader: string,
styleCodes: string,
skuCodes: string[],
productPriceMap: Map<string, number>,
fulfillmentGroupIds: Set<number>): Promise<Map<string, Product>> {
const productDetailsMap: Map<string, Product> = new Map();
const productSummaryDsResponse = await this.productDetailsDataLoader.getProductSummaryGroupLoader.load({
authHeader: authHeader,
styleCodes: styleCodes
});
let promises = productSummaryDsResponse
.ProductDetails
.Results
.map(result => {
result
.CustomAttributes
.forEach(async customAttr => {
const product_attributes = JSON.parse(customAttr.Value);
let fulfillmentGroupId =
(product_attributes.Details.FulfillmentGroupId
&& product_attributes.Details.FulfillmentGroupId.Value)
|| -1;
fulfillmentGroupIds.add(fulfillmentGroupId);
await this
.buildProductFromAttributes(authHeader,
product_attributes,
skuCodes,
productPriceMap)
.then(product => productDetailsMap.set(product.styleSkuDetails.sku, product));
})
})
return Promise
.all(promises)
.then(() => productDetailsMap);
}
private async buildProductFromAttributes(authHeader: string,
product_attributes: any,
skuCodes: string[],
productPriceMap: Map<string, number>): Promise<Product> {
let product = new Product();
[product.id, product.scode, product.title, product.isActive, product.styleSkuDetails, product.dUrl, product.iUrls]
= await Promise.all([this.getProductId(product_attributes), //async function
this.getProductScode(product_attributes), //async function
this.getProductTitle(product_attributes), //async functions
this.isProductActive(product_attributes), //async functions
this.getProductStyleSkuDetails(authHeader, product_attributes, skuCodes, productPriceMap), //async functions
this.getProductDUrl(product_attributes), //async functions
this.getProductIUrls(product_attributes)]); //async functions
return product;
}