I am using loadash map function to do some structuring of data. The data returns a set of ids for which i need to query the db and add the result to the map and then return but the data is returned later and my function returns first. How to make the return of map wait and then return in function.
let result = _.chain(value)
.groupBy('pubId')
.pairs()
.map(function(currentItem) {
let item = _.object(_.zip(['ID', 'targetting'], currentItem));
propsToBeDeleted.forEach(function(prop) {
item.targetting.forEach(d => {
item.publishername = d.RTB.name;
item.type = d.type;
delete d[prop];
});
});
item.targetting.map(d => {
if (d.type == 15) {
d.name = Object.keys(JSON.parse(d.value));
d.value = Object.values(JSON.parse(d.value))[0];
item.dspIds = [];
}
if (d.type == 16) {
let value = JSON.parse(d.value);
d.name = Object.keys(JSON.parse(d.value)).filter(d => d != 'profileId');
d.value = value;
item.dspIds = d.value.profileId;
dspAccount.find({where: {id: 139}}, (err, data) => {
// async call wait here to get data and attach to item
item.x = data ;
});
delete d.value.profileId;
d.value = JSON.stringify(d.value);
}
});
return item;
})
.value();
I also tried using promises
promises.push(new Promise((resolve, reject) => {
if (data.id) {
XX.upsertWithWhere({id: data.id}, payload, (err, data) => {
if (err) {
return reject(err);
}
return resolve(data);
});
}
}));
});
Promise.all(promises).then((data) => {
callback(null, data);
}, err => {
callback(err);
});
Update i have already listed the promise .all method that doesnot work . So it cannot be called duplicate