1

Ubuntu 20
Node 12.18.4
NPM 6.14.6
Sequelize 6.3.5

I followed the official guide and am so confused now.
After successfully configured Sequelize and connected, I tried to run (from official documentation)

await sequelize.authenticate();

It throws SyntaxError: await is only valid in async function.

Under the official get started page https://sequelize.org/master/manual/getting-started.html, it clearly states:

Most of the methods provided by Sequelize are asynchronous and therefore return Promises. They are all Promises , so you can use the Promise API (for example, using then, catch, finally) out of the box.
Of course, using async and await works normally as well.

ptree
  • 114
  • 12
  • The methods return promises, that's true but the problem is that the function *where you have the `await`* must be `async function` (or an async arrow function `async () => {}`). It literally has to have the `async` word there. – VLAZ Sep 29 '20 at 06:38

2 Answers2

2

That means in your function if you have to await you need to declare an async outside function:

async function() {
     await sequelize.authenticate();
}

or

const nameYourFunction = async () => {
     await sequelize.authenticate();
}

Remember to declare async before await or you can use the promise if you don't want to declare async await

const nameYourFunction = () => {
  sequelize
    .authenticate()
    .then((result) => {
      console.log('nameYourFunction -> result', result);
    })
    .catch((error) => {
      console.log('nameYourFunction -> error', error);
    });
};
Anhdevit
  • 1,926
  • 2
  • 16
  • 29
1

You have to use async function like this

getStateById: async (req, res) => {
              ^^^^^^

    sequelize.sequelize.transaction(async (t1) => {

        let state = await sequelize.state.findOne({
            where: {
                id: req.params.id
            }
        });

        let result = error.OK;
        result.data = state;

        logger.info(result);
        return res.status(200).send(result);
    }).catch(function (err) {
        logger.error(err);
        return res.status(500).send(error.SERVER_ERROR);
    });
}

async is necessary when you want to use await in your app it will be only used in async function type

Aryan
  • 3,338
  • 4
  • 18
  • 43