5

I am writing a node API and want to save the results of a Sequelize query in a variable as a plain JavaScript object outside of the findAll block. I have something that works, but not as well as I would like. Here is what I have:

router.get('/', (req, res, next) => {

    models.User.findAll({
        attributes: ['id', 'name'],
        raw: true
    }).then(function (results) {

        console.log(results); // Plain JavaScript object, which is good

        // Do logic on results 

        //Return results
        res.status(200).json({
            results
        });
    });
});

But I really don't want to keep all my logic within the then() block, especially since I might want to do some other queries before or after this one. I really want something like (if this was a thing):

router.get('/', (req, res, next) => {

    var users = models.User.findAll({
        attributes: ['id', 'name'],
        raw: true
    }).then(function (results) {            
        });
    });

    // Do logic on results

    // return results
    res.status(200).json({
        results
    });
});

I tried to save the sequelize query in a function below the router.get() call and return the results while they were a JavaScript object, but that didn't work. I am very new to JavaScript, so I appreciate the advice.

1
  • you can use async-await. Commented Aug 5, 2018 at 3:02

2 Answers 2

2

Well, if you don't want your logic code in the then block, you might as well use async-await:

router.get('/', async (req, res, next) => {

    var results = await models.User.findAll({
        attributes: ['id', 'name'],
        raw: true
    });

     // you've result variable available here, use it.
    // Do logic on results

    // return results
    res.status(200).json({
        results
    });
});

now you don't have to write the code in then block, you can just use the variable results in the function directly.

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

2 Comments

Wow, perfect! Thanks!
happy to help mate :))
0

my friend is very simple to do logic on your result in same place that your retrieve you data for example in your code that i modify :

router.get('/', (req, res, next) => {
     var users = models.User.findAll({
            attributes: ['id', 'name'],
            raw: true
        }).then((results) => {            
            //here do you logic with results 
              //after
                res.status(200).json({data : result});
        }).catch(error => res.status(400).json({error}));
});

Comments

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.