簡體   English   中英

await 僅在異步函數和模塊的頂層主體中有效

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

我正在嘗試連接到谷歌客戶端 API,但它說 await 僅在關於const client的異步函數中有效。 但是有等待和異步嗎?

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");
});

我們只能在 async 函數中使用await 在這里您使用了 await 但它不在 async 函數內。

這里可以使用then-catch代替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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM