I started learning about JavaScript Promises today. I'm working in a NodeJS environment with multiple modules. Just to get an better understanding how a promise works, I've made a test function that resolves the promise after 5 seconds. This is what I did:
const utils = require('./utils');
const labels = {
init(req, res, next) {
utils.loopDates(options).then(build.init(options, req, res, next));
}
};
In the utils.loopDates()
function I do the following:
const utils = {
loopDates(options) {
return new Promise((resolve, reject) => {
options.test = 'test';
setTimeout(function() {
resolve(options)
}, 5000)
});
}
}
module.exports = utils;
This is my understanding of what should happen; the promise resolves after 5 seconds and then the build.init
function fires. But what actually happens is that the build.init
function fires immediately. The promise seems to ignore the timeout.
It could be that my understanding of Promises is wrong, but I'm not sure what I am doing wrong here. Hope someone can help me out.
Cheers