admin管理员组文章数量:1317915
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
本文标签: javascriptPromise in Lodash mapStack Overflow
版权声明:本文标题:javascript - Promise in Lodash map - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742025490a2415463.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论