最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Promise in Lodash map - Stack Overflow

programmeradmin2浏览0评论

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 badges
Add a ment  | 

3 Answers 3

Reset to default 5

I 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

发布评论

评论列表(0)

  1. 暂无评论