Given that promise1 and promise2 are correctly resolved with the below code:
export const getExistingPayments = async (payments: Payment[]) => {
const promise1 = await getPayment(payments[0].paymentId)
const promise2 = await getPayment(payments[1].paymentId)
const results = [promise1, promise2]
return results
}
Can anybody help explain why the below code would just hang, the promises are never resolved or rejected:
export const getExistingPayments = async (payments: Payment[]) => {
const promise1 = getPayment(payments[0].paymentId)
const promise2 = getPayment(payments[1].paymentId)
const results = await Promise.all([promise1, promise2])
return results
}
It might also be worth mentioning that when only one promise is passed to the Promise.all the promise is resolved as expected, the below code also works fine:
export const getExistingPayments = async (payments: Payment[]) => {
const promise1 = getPayment(payments[0].paymentId)
const results = await Promise.all([promise1)
return results
}
CodePudding user response:
Try something like this, instead of assigning the result of the functions to a variables
const [results1, result2] = await Promise.all([
getPayment(payments[0].paymentId),
getPayment(payments[1].paymentId)
])
CodePudding user response:
This largely depends on what happens inside getPayment
. In general, your second example should work, but there are cases when that does not happen, particularly, if the two getPayment
calls, due to some internal operations wait for each-other, reaching a deadlock.
While based on the information you have given, we cannot tell you exactly what happens in your code, the solution that you apply should be that you ensure that getPayment
calls will never cause a deadlock if they are executed asynchronously.