Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

await is only valid in async functions and the top level bodies of modules

I’m trying to connect to the google client API, but it’s saying await is only valid in async functions regarding the const client. But there is an await and async?

const express = require("express");
const { google } = require("googleapis");
require("dotenv").config();

let testENV = JSON.parse(process.env.GOOGLE_ENV);

const app = express();

app.get("/", async (req, res) => {
  const auth = new google.auth.GoogleAuth({
    keyFile: "testENV",
    scopes: "https://www.googleapis.com/auth/spreadsheets",
  });
});

const client = await auth.getClient();

app.listen(3000, (req, res) => {
  console.log("Running on 3000");
});

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

We can only use await, inside the async function. Here you have used the await but that is not inside the async function.

Here you can use then-catch, instead of the await

const express = require("express");
const { google } = require("googleapis");
require("dotenv").config();

let testENV = JSON.parse(process.env.GOOGLE_ENV);

const app = express();

app.get("/", async (req, res) => {
  const auth = new google.auth.GoogleAuth({
    keyFile: "testENV",
    scopes: "https://www.googleapis.com/auth/spreadsheets",
  });
});

const client = auth.getClient()
.then((client) => {
  console.log(client)
  app.listen(3000, (req, res) => {
  console.log("Running on 3000");
});
})
.catch((error) => {console.log(error)})
const express = require("express");
const { google } = require("googleapis");
require("dotenv").config();

let testENV = JSON.parse(process.env.GOOGLE_ENV);

const app = express();

async function start() {
  app.get("/", async (req, res) => {
  const auth = new google.auth.GoogleAuth({
    keyFile: "testENV",
    scopes: "https://www.googleapis.com/auth/spreadsheets",
  });
});

const client = await auth.getClient();

app.listen(3000, (req, res) => {
  console.log("Running on 3000");
});
}

start()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading