async await 不能与 Node.js gdrive API v3 一起使用

async await not working with Node.js gdrive API v3

希望你能帮我解决这个问题。很困惑为什么这会给我带来问题。

按照快速入门指南,我能够将文件打印到控制台。太棒了,我看到 files.list 中的第二个参数是传入 res/error

的回调

节点:v8.3.0 npm: v5.3.0

const { google } = require('googleapis');
const express = require('express');
const fs = require('fs');
const keys = require('./credentials.json');

const app = express();

const drive = google.drive('v3');

const scopes = [
  "https://www.googleapis.com/auth/drive",
  "https://www.googleapis.com/auth/drive.file",
  "https://www.googleapis.com/auth/drive.metadata.readonly"
];

// Create an oAuth2 client to authorize the API call
const client = new google.auth.OAuth2(
  keys.web.client_id,
  keys.web.client_secret,
  keys.web.redirect_uris[0]
);

// Generate the url that will be used for authorization
this.authorizeUrl = client.generateAuthUrl({
  access_type: 'offline',
  scope: scopes
});

// Open an http server to accept the oauth callback. In this
// simple example, the only request to our webserver is to
// /oauth2callback?code=<code>
app.get('/oauth2callback', (req, res) => {
  const code = req.query.code;
  client.getToken(code, (err, tokens) => {
    if (err) throw err;

    client.credentials = tokens;
    // set auth as a global default
    google.options({
      auth: client
    });

    listFiles()
    res.send('Authentication successful! Please return to the console.');
    server.close();
  });
});
// This prints out 10 files, all good.
function listFiles() {

  drive.files.list({
    pageSize: 10,
    fields: 'nextPageToken, files(id, name)',
    q: "name = 'US'"
  }, (err, res) => {
    if (err) {
      console.error('The API returned an error.');
      throw err;
    }
    const files = res.data.files;
    if (files.length === 0) {
      console.log('No files found.');
    } else {
      console.log('Files:');
      for (const file of files) {
        console.log(`${file.name} (${file.id})`);
      }
    }
  });
}

具体来说,当我尝试使用 async/await 时,listFiles 功能不起作用。

这是它的样子:

async function listFiles() {
  const res = await drive.files.list({
    pageSize: 10,
    fields: 'nextPageToken, files(id, name)',
    q: "name = 'US'"
  });
  console.log(res);
  return res;
}

正在记录 undefined。有任何想法吗?谢谢!

我所要做的就是 npm uninstall googleapis 然后 npm install googleapis --save 就成功了。超级奇怪,但很高兴我能够使用 async/await =)

清理我的代码