Node.js async function not being recognized as a valid async function

Viewed 360

I've got these 2 functions

async function movieExists(movie){
        return new Promise((resolve, reject) => {
            const sql = '...';

            con.query(sql, (err,result,fields) => {
                if(err)
                    throw err;
                else if(!result[0])
                    reject("Error");
                else
                    resolve(result[0].total);
            })
        })
}
async function addMovie(movie){
        return new Promise((resolve, reject) => {
            const sql = '...';
            const exists = await movieExists(movie); //Error on this line

            if(exists == 0){
                con.query(sql, (err,result,fields) => {
                    if(err)
                        reject("Error");
                    else   
                        resolve("Success");
                })
            }else
                resolve("Movie already exists");
        })
}

Error : SyntaxError: await is only valid in async function

Node version -> v10.16.0

**If you have any suggestions for the code itself I would be glad to hear them.

2 Answers

The await keyword is directly inside the function that you are passing to new Promise(), which is not async.

Try moving it outside that function, like this:

async function addMovie(movie){
  const exists = await movieExists(movie);
  return new Promise((resolve, reject) => {
    const sql = '...';
    // ...
  })
}

The second condition is wrong because in the Promise the anonymous function is not async function you can use the following instead, but it is not a good way to control the sequence of async.

async function addMovie(movie){
        return new Promise(async (resolve, reject) => {
            const sql = '...';
            const exists = await movieExists(movie); //Error on this line

            if(exists == 0){
                con.query(sql, (err,result,fields) => {
                    if(err)
                        reject("Error");
                    else   
                        resolve("Success");
                })
            }else
                resolve("Movie already exists");
        })
}
Related