How do I return a value from a promise to my calling function?
In httpGet()
, do resolve({ contID, gallons, /* ... */ })
, and then in then((response) => {})
your response
will be an object with contID
, gallons
, etc. properties. Check out this blog post for more details on async return values.
How do I return value from promise in javascript?
Your code should look like this:
router.get('/', async (req, res) => {
try {
const contacts = await Contact.find()
const nextBirthdays = getNextBirthdays(contacts)
res.json({ contacts, nextBirthdays });
} catch (error) {
res.status(500).json({ message: error.message })
}
})
function getNextBirthdays(contacts) {
let nextBirthdays = [];
contacts.forEach(contact => {
let daysTillBirthday = getDaysTillBirthday(contact.dob)
if (daysTillBirthday < 10 && daysTillBirthday > 0) {
console.log(`${contact.firstname}'s birthday is in ${daysTillBirthday} days`)
nextBirthdays.push({
firstname: contact.firstname,
days: daysTillBirthday
})
}
})
// Returns object with next birthdays
return nextBirthdays
}
function getDaysTillBirthday(_birthday) {
const birthday = birthdayDayOfYear(_birthday);
const today = dayOfTheYear();
return birthday - today;
}
function birthdayDayOfYear(date) {
const now = date;
const start = new Date(now.getFullYear(), 0, 0);
const diff = now - start;
const oneDay = 1000 * 60 * 60 * 24;
return Math.floor(diff / oneDay);
}
function dayOfTheYear() {
const now = new Date();
const start = new Date(now.getFullYear(), 0, 0);
const diff = now - start;
const oneDay = 1000 * 60 * 60 * 24;
return Math.floor(diff / oneDay);
}
module.exports = router;
how to return value from a promise function
If that's the case you can do like this
const getStatus = async () => {
try {
const hosts = [device];
const promises = [];
hosts.forEach((host) => {
promises.push(ping.promise.probe(host));
});
const result = await Promise.all(promises);
const status = result.map((r) => { return r.alive; });
return status;
} catch (err) {
logger.error(err, '[ config - findDevices() ]');
return { status: 'Failed' };
}
};
How to return data from promise
One of the fundamental principles behind a promise is that it's handled asynchronously. This means that you cannot create a promise and then immediately use its result synchronously in your code (e.g. it's not possible to return the result of a promise from within the function that initiated the promise).
What you likely want to do instead is to return the entire promise itself. Then whatever function needs its result can call .then()
on the promise, and the result will be there when the promise has been resolved.
Here is a resource from HTML5Rocks that goes over the lifecycle of a promise, and how its output is resolved asynchronously:
https://web.dev/promises/
How to return value from a promise that's inside another function?
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 = async function(req, res) {
try{
req.body.payment = await exports.create_booking_payment(req.body.total_amount);
console.log(req.body.payment);
var new_booking = new Booking(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 = new Booking(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
})
}
});
});
}
Related Topics
Access JavaScript Property Case-Insensitively
Js Replace Not Working on String
How to Save a Leaflet Map with Drawn Shapes/Points on It in Shiny
Change Second Select List Based on First Select List Value in Rails
Js.Erb Not Executing JavaScript But Is Processed Rails
How to Detect Scroll Position of Page Using Jquery
Why Is the Ecc-Dh Symmetric Key of This Site Different from Openssl
Display Spinner While Datatables Table Loads Ruby on Rails
Javascript:For Loop with Timeout
Mediastream Capture Canvas and Audio Simultaneously
How to Invoke Ruby from Node.Js
JavaScript Module Pattern with Example
Merge Keys Array and Values Array into an Object in JavaScript
How to Use JavaScript in Ruby on Rails
How to Get the Content of the File Specified as the 'Src' of a <Script> Tag
Fire Jquery Event on Div Change
Determine Which Element the Mouse Pointer Is on Top of in JavaScript