How To Return Value From A Promise That's Inside Another Function?
Solution 1:
You seem to have missed that an async
function still returns a promise, not the actual value. So, when you call create_booking_payment()
, you are getting back a promise that you need to use either .then()
with or await
with. There's no free lunch across a function boundary. await
allows you to program in a synchronous-like fashion inside a function, but still does not allow you to return the value from the function. When it looks like you're returning the value from the async
function, you're actually returning a promise that resolves to that value.
So, you'd do this with async
and await
:
exports.create_booking = asyncfunction(req, res) {
try{
req.body.payment = awaitexports.create_booking_payment(req.body.total_amount);
console.log(req.body.payment);
var new_booking = newBooking(req.body);
new_booking.save(function(err, booking) {
if (err)
res.status(500).send(err);
else
res.json(booking);
});
} catch(e) {
res.status(500).send(err);
}
};
or this with .then()
:
exports.create_booking = function(req, res) {
exports.create_booking_payment(req.body.total_amount).then(payment => {
console.log(payment);
req.body.payment = payment;
var new_booking = newBooking(req.body);
new_booking.save(function(err, booking) {
if (err)
res.status(500).send(err);
else
res.json(booking);
});
}).catch(err => {
res.status(500).send(err);
});
};
Note, I also added more complete error handling to both scenarios. Also, this code would be a lot cleaner if you "promisfied" or used an already promisified interface for your .save()
method. I strongly dislike using plain callback async code inside of promise-based code because it ends up duplicating error handling (like you see in this case).
Also, create_booking_payment()
doesn't need to be async
or use await
since all you need it to do is to return your promise which it already knows how to do:
exports.create_booking_payment = function() {
return new Promise (function(resolve, reject) {
mollie.payments.create({
amount: 20.00,
description: "Reservation code: ",
redirectUrl: "https://www.website.com/",
webhookUrl: ""
}, function(payment) {
if (payment.error) reject(payment.error)
else { resolve({
id: payment.id,
link: payment.getPaymentUrl(),
status: payment.status
})
}
});
});
}
Post a Comment for "How To Return Value From A Promise That's Inside Another Function?"