Search code examples
javascriptnode.jsmean-stack

Undefined return in a 'then' chain


I am building an app with node and angular and when I request this specific endpoint, I am getting returned with an empty array '[]'. I put the return statement in the final 'then' block, but this gets executed before the prior for loop.

How can I make this synchronous so that the realTemps array gets populated in the for loop, then it gets returned in the next then statement?

router.get("", (req, res, next) => {
var templates = [];
var realTemps = [];
const token = req.headers.authorization.split(" ");
const decoded = jwt.verify(token[1], 'secretkey');
decodedFactoryId = decoded.factoryId

Template.findAllByFactoryId(decodedFactoryId)
    .then((results) => {
        for (var i = 0; i < results.length; i++) {
            // THIS IS AN AVOIDABLE LOOP, quadratic time must be prevented by correctly formatting the data (TODO)
            for (var j = 0; j < results.length; j++) {
                if (results[i][j].id) {
                    templates.push(results[i][j].id)
                }
            }
        }
    }).then(() => {
        console.log("templates: " + templates)
        for (var i = 0; i < templates.length; i++) {
            console.log(templates[i])
            Template.findByTemplateId(templates[i]).then(result => {
                console.log("here is the result: " + JSON.stringify(result[0]))
                realTemps.push(result);
            })

        }
    })
    .then(() => {
        return realTemps;
    })
 })

Solution

  • simply make the second and third .then as follows

    .then(() => Promise.all(templates.map(template => Template.findByTemplateId(template))))
    .then((realTemps) => {
        return realTemps;
    })