I have the below map and filter functions doing async inside.
console.log('kycPendingProviders:', kycPendingProviders)
const incompleteKYCClaims = kycPendingProviders
.map(async (p) => {
const provider = await getProviderOrThrow(p.tin)
console.log('provider:', provider)
// check who submitted the current KYC
if (provider.kycSubmissionInfo?.submissionRequest.submitterUUID !== currentUserID) return Promise.reject()
return toProviderRelationshipClaims({ tin: p.tin, role: ProviderUserSubRoles.ky, status: 'KYCInDraft' })
})
.filter((claim) => claim) as unknown as Array<ProviderRelationshipClaims>
console.log('incompleteKYCClaims:', incompleteKYCClaims)
Tried both if (provider.kycSubmissionInfo?.submissionRequest.submitterUUID !== currentUserID) return with the idea that filter will remove undefined entries and if (provider.kycSubmissionInfo?.submissionRequest.submitterUUID !== currentUserID) return Promise.reject() versions.
When the condition is not met, I am getting as a result [ Promise { <pending> } ] while I need an undefined value to be removed from the results array by the subsequent filter().
I have a version with for of loop. That seemed to be working correctly. Why is map() not returning a value [here undefined], but a pending promise? How do I fix this?
Thank you
>Solution :
To fix this issue and obtain the desired behavior, you can use Promise.all() to await all the promises returned by map() and then use the filter() function on the resolved values. Here’s an example:
console.log('kycPendingProviders:', kycPendingProviders);
const incompleteKYCClaims = await Promise.all(
kycPendingProviders.map(async (p) => {
const provider = await getProviderOrThrow(p.tin);
console.log('provider:', provider);
if (provider.kycSubmissionInfo?.submissionRequest.submitterUUID !== currentUserID) {
return undefined; // or null, or any other value that signifies removal
}
return toProviderRelationshipClaims({ tin: p.tin, role: ProviderUserSubRoles.ky, status: 'KYCInDraft' });
})
);
const filteredKYCClaims = incompleteKYCClaims.filter((claim) => claim !== undefined) as Array<ProviderRelationshipClaims>;
console.log('filteredKYCClaims:', filteredKYCClaims);