I am really new to promises in javascript so I really don't understand what I may be missing in my code. Basically my problem is that in my main program I am trying to iterate through a json array using async.forEachOf
and inside that I am calling the DAO.processData
and after completing the loop I want to send the response. If there is a better solution to this please do help.
Now here I am trying to access a value from another module that is returning a promise object along with a value. The promise returning module looks like below:
var dao = {}
dao.processData = function(data) {
var finalPromise = new Promise(()=>{});
async.waterfall([function1, function2, function3], someCallBackFunction);
someCallBackFunction = function () {
console.log('in some function');
finalPromise = new Promise( (resolve,reject) => {
resolve(data++);
})
return finalPromise;
}
}
module.exports = dao
The module receiving the data looks like below.
const DAO = require('./myObject')
var myArray = [1, 2]
var jsonResponse = {}
someRouterFunction = function (req, res) {
async.forEachOf(myArray, (number) => {
Promise.resolve(DAO.processData(number)).then( prepareResponse )
.catch ( e => { console.log(e) } );
}, (err) => {
res.json(jsonResponse);
})
}
function prepareResponse (res) {
jsonResponse = {
'msg': res
}
}
someRouterFunction();
With this code it returns cannot read propety 'then' of undefined
. So I did the following in the someRouterFunction
:
Promise.resolve(DAO.processData(number)).then( prepareResponse );
This makes the call to the function but I am never able to access the returned value which is res
here in the prepareResponse
function.