异步等待无法使用Node.js gdrive API v3

时间:2018-05-04 00:32:47

标签: node.js google-drive-api google-drive-team-drive

希望你能帮我解决这个问题。非常难过为什么这会给我带来问题。

按照快速入门指南,我可以将文件打印到控制台。很酷,我看到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。有任何想法吗?谢谢!

1 个答案:

答案 0 :(得分:4)

我所要做的就是npm uninstall googleapis,然后是npm install googleapis --save,这就是诀窍。超级奇怪,但很高兴我能用async / await来清理我的代码=)