I am trying to return a Promise object ever 1000ms, but i am not sure how to access the data returned in the Promise when it is inside a setInterval()
callback.
EDIT I appears i was not being very clear as to my intentions, so i will try and explain what it is i am trying to do. I making a count down where by the necessary calculations are are don every 1000ms based on specified end date.
Here is the code that provides the return value i would like returned as a Pormise value every 1000ms:
calculateTimeRemaining(endDate: string) {
const { secondsInDay, daysOfYear, secondsInHour, secondsInMinute } = this.unitsOfTime;
let distance: number =
(Date.parse(new Date(endDate).toString()) - Date.parse(new Date().toString())) / this.increment;
if (distance > 0) {
// Years left
if (distance >= daysOfYear * secondsInDay) {
// 365.25 * 24 * 60 * 60
this.timeRemaining.years = Math.floor(distance / (daysOfYear * secondsInDay));
distance -= this.timeRemaining.years * daysOfYear * secondsInDay;
}
// Days left
if (distance >= secondsInDay) {
// 24 * 60 * 60
this.timeRemaining.days = Math.floor(distance / secondsInDay);
distance -= this.timeRemaining.days * secondsInDay;
}
// Hours left
if (distance >= secondsInHour) {
// 60 * 60
this.timeRemaining.hours = Math.floor(distance / secondsInHour);
distance -= this.timeRemaining.hours * secondsInHour;
}
// Minutes left
if (distance >= secondsInMinute) {
// 60
this.timeRemaining.minutes = Math.floor(distance / secondsInMinute);
distance -= this.timeRemaining.minutes * secondsInMinute;
}
// Seconds left
this.timeRemaining.seconds = distance;
}
return this.timeRemaining;
}
Example:
const interval = window.setInterval(() => {
return new Promise((resolve, reject) => {
resolve('Hello');
});
}, 1000);
How to i access the Promise object with .then()
afterwards?
Does not work:
interval.then((data) => console.log(data);
setInterval
returns the interval reference, it does not return the callback's return. Besides, a promise can only be resolved once. What are you trying to accomplish? – Buddereturn
once, not "every 1000 ms" – Sustenance