I'm writing a service in NodeJS which retrieves a list of Items. For each one, I have to create a counter that indicates the amount of available items. So, if the item is present in the store, the counter simply increments and resolves the promise (because I'm sure there will be at most one in stock).
Otherwise, if it is in the stock, I have to check the exact number of available pieces.
If it is not one of the two previous cases, I'll resolve the promise and I pass to the next item.
The problem is in the second case, because before resolve the main promise (of the current item) I have to wait for the call to retrieve the part counter in the warehouse is over. As it is an asynchronous code, when it currently enter in the second "else", it triggers the call for the piece counter in the stock and immediately resolves the promise, without waiting for the end of the call. How can I solve this concatenation of promises?
This is the code:
let promises: any[] = [];
for (let i = 0, itemsLength = itemList.length; i < itemsLength; i++) {
let currentItem = itemList[i];
promises.push(
new Promise(function(resolve: Function, reject: Function) {
act({
...call the service to retrieve the item list
})
.then(function(senecaResponse: SenecaResponse < any > ) {
if (senecaResponse && senecaResponse.error) {
reject(new Error(senecaResponse.error));
}
currentItem.itemDetails = senecaResponse.response;
currentItem.counters = {
available: 0
};
if (currentItem.itemDetails && currentItem.itemDetails.length) {
for (let k = 0, detailsLength = currentItem.itemDetails.length; k < detailsLength; k++) {
let currentItemDetail = currentItem.itemDetails[k];
if (currentItemDetail.val === "IN_THE_STORE") {
currentItem.counters.available++;
resolve();
} else if (currentItemDetail.courseType === "IN_STOCK") {
act({
...call the service to retrieve the counter in stock
})
.then(function(stockResponse: SenecaResponse < any > ) {
if (stockResponse && stockResponse.error) {
reject(new Error(stockResponse.error));
} else {
currentItem.counters.available = stockResponse.response;
}
resolve();
})
.catch(function(error: Error) {
options.logger.error(error);
reject(error);
})
} else {
resolve();
}
}
} else {
resolve();
}
})
.catch(function(error: Error) {
options.logger.error(error);
reject(error);
})
})
);
}
return Promise.all(promises);