async не работает с Node.js gdrive API v3 - PullRequest
0 голосов
/ 04 мая 2018

в надежде, что вы поможете мне понять это. Довольно озадачен тем, почему это вызывает у меня проблемы.

Следуя краткому руководству, я могу вывести файлы на консоль. Круто, я вижу второй аргумент в 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})`);
      }
    }
  });
}

В частности, функция listFiles не работает, когда я пытаюсь использовать async / await.

Вот как это выглядит:

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 голосов
/ 04 мая 2018

Все, что мне нужно было сделать, это npm uninstall googleapis, а затем npm install googleapis --save, и это сработало. Очень странно, но рад, что смог очистить свой код с помощью async / await =)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...