0

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?

0

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Ok so the key was placing the promises into an array first then running them at the same time.. with promise.all() which I didn't know about.. Thanks!
No problem. A general rule of thumb that I've found is that if you are using promises in a loop, you need to use Promise.all()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.