Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Promise.map over object

I've an object like;

{ '6': { stream: { twitch: [Object] } },
  '7': { stream: { twitch: [Object] } },
  '8': { stream: { twitch: [Object] } },
  '9': { stream: { twitch: [Object] } },
  '10': { stream: { twitch: [Object] } },
  '11': { stream: { twitch: [Object] } } }

I want to iterate over it like;

return Promise.map(myObj, function(minute, minuteIndex) {

so basically minute should hold the data and minuteIndex should be holding the index.

I can do it with lodash but bluebird can't somehow.

_.forEach(hour.minutes, function(minute, minuteIndex) {

I know that this code was working before but now can't get it so.

Any ideas?

like image 201
HuseyinUslu Avatar asked Mar 11 '23 12:03

HuseyinUslu


2 Answers

You can map the object's keys into an array and give that to Promise.map():

function process(stats) {
    var statsArray = Object.keys(stats).map(key => ({
        minute: key, minuteIndex: stats[key]
    }));
    return Promise.map(statsArray, item => {
        // work with item.minute & item.minuteIndex
    });
}

Usage:

var twitchStats = {
  '6': { stream: { twitch: [Object] } },
  '7': { stream: { twitch: [Object] } },
  '8': { stream: { twitch: [Object] } },
  '9': { stream: { twitch: [Object] } },
  '10': { stream: { twitch: [Object] } },
  '11': { stream: { twitch: [Object] } }
};

process(twitchStats).then(result => {
    // ...
});
like image 53
Tomalak Avatar answered Mar 23 '23 20:03

Tomalak


Promise.all(

  Object.keys(twitchStats).map(key => Promise.resolve({
        minute: key, minuteIndex: twitchStats[key]
    })

)

Use combination of Promise.all() with map() functions. Be careful: map() has to return promise in order for Promise.all() work.

like image 42
RepiatX Avatar answered Mar 23 '23 20:03

RepiatX