hope1234
hope1234

Reputation: 47

Looping a javascript promise to append to an array

Good day, below I have

    var request = require('request');
    getFood = function(lst){
        return new Promise(function(resolve, reject){
            //console.log(lst)
            request('https://api.jamesoff.net/recipe', function (error, response, recipe) {
                lst.push(JSON.parse(recipe))
                resolve(lst);
            })
        });
    }   


    getFood([]).then(function(data){
        for(var i = 0; i < 3; i++){
            getFood(data)
        }
        return(data);
    }).then(function(data){
        console.log(data)
    })

What I am aiming to accomplish is by using a promise chain place three recipies into an array using a loop. I only get one item and I know why this occurs, however I can't wrap my head around the procedure to accomplish my goal. Could I please get an explanation with code?

Upvotes: 0

Views: 3202

Answers (1)

BShaps
BShaps

Reputation: 1414

The problem is your getFood call in a loop. If you are looping through promises the best way to do it is with Promise.all()

An example:

var promiseArray = [];
for(var i = 0; i < 3; i++){
    promiseArray.push(getFood(data))
}
Promise.all(promiseArray).then(function(values) {
    // values is array of resolve values in the order that promises were pushed into the array
});

This resolves the promises in the order in which they were called and should help with your issues.

Upvotes: 5

Related Questions