Thursday 15 December 2016

javascript - Node JS access value outside callback

I have a problem access value outside callback, I have a json like below



[ { Latitude: '3.59288601404616',
Longitude: '98.6827551573515',
Latitude1: '3.5828173285855724',
Longitude1: '98.69136337190866',

},
{ Latitude: '3.65865664490563',
Longitude: '98.6652326211333',
Latitude1: '3.5828173285855724',
Longitude1: '98.69136337190866',
} ]


I have read a lot of web said that its impossible to get value from the callback because we have to wait until the callback finish first then we can have a value and some question in stackoverflow provide some solution but no one is work for me.




What I want to get is to add a new json inside that json that I post above, I want to add Distance json inside so I use node-google-distance



What I want is like this



[ { Latitude: '3.59288601404616',
Longitude: '98.6827551573515',
Latitude1: '3.5828173285855724',
Longitude1: '98.69136337190866',
Distance '10127'
},

{ Latitude: '3.65865664490563',
Longitude: '98.6652326211333',
Latitude1: '3.5828173285855724',
Longitude1: '98.69136337190866',
Distance: '1836'
} ]


and my code like this




models.xxxx.findAll({
where: {
UserId: req.params.UserId
},
attributes: ['Latitude', 'Longitude', [sequelize.literal('(SELECT Latitude FROM `xxxx` WHERE `id` = ' + req.params.MerchantId + ')'), 'Latitude1'],
[sequelize.literal('(SELECT Longitude FROM `xxxx` WHERE `id` = ' + req.params.MerchantId + ')'), 'Longitude1']
]
}).then(function(lists) {

var json = JSON.parse(JSON.stringify(lists));


function get_count(item, callback) {
var array = [];
for (var i = 0; i < json.length; i++) {
distance.get({
origin: json[i].Latitude1 + ',' + json[i].Longitude1,
destination: json[i].Latitude + ',' + json[i].Longitude
},
function(err, data) {
if (err) {

array.push(0);
} else {
array.push(data.distanceValue);
}

item.distanceValue = array;
});
}
callback(null, item);
}

async.map(json, get_count, function(err, results) {
console.log(results);
});
});


I use async.map because in this web someone post it
Javascript: return a value to a variable outside of a callback function, I spend a lot of time search in stackoverflow but found nothing



NodeJS Can't Access Variable Inside Callback




How to return value from an asynchronous callback function?



NodeJS get async return value (callback)



Site 1



Site 2



Please give me some hint or some example how to fix this problem

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...