-1
我在Node.js中存在变量持久性的问题。如何在回调之外使用变量
我做这个程序:
var travelTimes;
for(var i = 0; i < data.length; i++){
distance.get(
{
origin: hotel,
destination: data[i].ubicacion,
language: 'es'
},function(err, maps_data) {
if (err) return console.log(err);
travelTimes.push(data.ubication);
});
}
console.log(travelTimes);
最后一行给我undefined
。我在搜索并发现它是因为Node.js是异步的,我的变量maps_data
只存在于distance.get()回调函数中,但我需要这些数据来继续我的工作。我怎样才能让它活在我的所有代码中?谢谢!!