I'm using Lodash to map an array. In the loop, there's a promise to get something from an external API.
var array = _.map(data, function (d, i) {
getFromMyAPI(d[4])
.then(function (results) {
return {
id: d[0],
zoneLat: d[2],
zoneLon: d[3],
wifiLat: results.a,
wifiLon: results.b
};
});
});
But then, if I do
console.log(array);
it shows, of course, an empty array. How could I get the content of this array, after the mapping is done?
I'm using Lodash to map an array. In the loop, there's a promise to get something from an external API.
var array = _.map(data, function (d, i) {
getFromMyAPI(d[4])
.then(function (results) {
return {
id: d[0],
zoneLat: d[2],
zoneLon: d[3],
wifiLat: results.a,
wifiLon: results.b
};
});
});
But then, if I do
console.log(array);
it shows, of course, an empty array. How could I get the content of this array, after the mapping is done?
Share Improve this question edited Apr 1, 2016 at 6:27 Mencls asked Apr 1, 2016 at 6:07 MenclsMencls 3392 gold badges6 silver badges15 bronze badges3 Answers
Reset to default 5I bet you've missed fact that getFromMyApi
call requires argument from iteration... let's assume that's true.
You should treat this array as result of Promise which is chained somehow to all results of getFromMyAPI
calls. Somehow is best done using some advanced promise library providing functional versions of classing map/reduce over promises like bluebird.
Example using bluebird:
var Promise = require('bluebird');
return Promise.map(data, function(d,i) {
return getFromMyApi(arguments, d).then(function(r) {
return {
id: d[0],
zoneLat: d[2],
zoneLon: d[3],
wifiLat: r.a,
wifiLon: r.b
};
})
}).then(function(array) {
console.log("#2", array);
});
You forgot return from the map function. The array should not be empty, but should contain the Promises.
Change it like this and it should work:
var array = [];
_.map(data, function (d, i) {
getFromMyAPI(d[4])
.then(function (results) {
array.push({
id: d[0],
zoneLat: d[2],
zoneLon: d[3],
wifiLat: results.a,
wifiLon: results.b
});
});
});
Edited