Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return complete array from Promise

I have a function that returns JSON objects using hnews.getById(id). I then push each story returned in the promise to an array. I'm having trouble figuring out how I'd then get the complete array. Do I need to use another promise?

function updateTopStories() {
    var storiesArr = [];

    hnews.getIdsInCategory('topstories', 60)
    .then(function(ids) {
        ids.forEach(function(id) {
            hnews.getById(id).then(function(story) {
                console.log(story);
                storiesArr.push(story);
            });
        });
    });

    return storiesArr;
}

var stories = updateTopStories();
console.log(stories); // Empty array

EDIT: I need to return storiesArr from updateTopStories();

like image 254
Cole Roberts Avatar asked May 14 '26 20:05

Cole Roberts


1 Answers

You are invoking multiple async processes here. A common way of handling this is to map your array of ids to an array of Promises which all have to resolve before returning. See if this works for you.

function updateTopStories() {

    return hnews.getIdsInCategory('topstories', 60).then(function(ids) {
        var promises = ids.map(function(id) {
            return hnews.getById(id);
        });
        return Promise.all(promises);
    });
}

updateTopStories().then(function(stories) {
    console.log(stories);
});
like image 186
DeezCashews Avatar answered May 16 '26 11:05

DeezCashews



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!