I am learning node and promises. I've simplified my problem and sharing my code below.
I have three modules: app.js, modLanguage.js and model.js
app.js:
var l = require('../test/modLanguage.js');
var params = [{
p0: 'johnDoe',
p1: '12345',
p2: 0
}];
var lang = l.call(params);
console.log("Needs to run last: " + lang.language);
modLanguage.js:
var call = function(params) {
var langQuery = require('../test/model.js');
var userLang = createLanguage();
userLang.setLanguage('FRENCH');
console.log("This needs to run first - setting lang French before DB dip: " + userLang.language);
var myData = langQuery.getLanguage(params)
// My DB dip
.then(function(data) {
var data = JSON.parse(JSON.stringify(data[0]));
userLang.setLanguage(data[0].Language);
console.log("Needs to run second - DB dip brought language ENG: " + userLang.language);
return userLang;
})
.catch(function(err) {
console.log('error');
});
return userLang;
}
module.exports.call = call;
function createLanguage() {
return {
language: this.language,
setLanguage: function(language) {
this.language = language;
return this.language;
}
}
}
model.js is a simple module which uses params, runs a stored procedure and brings back data by returning a promise.
I want to block the running of code at app.js until the object is initialized from the data returned against Database dip. However, as is, the console.log shows:
This needs to run first - setting lang French before DB dip: FRENCH
Needs to run last: FRENCH
Needs to run second - DB dip brought language ENG: ENG
What I want to achieve is obviously:
This needs to run first - setting lang French before DB dip: FRENCH
Needs to run second - DB dip brought language ENG: ENG
Needs to run last: ENG
Please, advice the changes I need to make to achieve that?
callif you want to wait on it inapp.js... and use.theninapp.jsbecause at the moment you are not using Promises correctly