【问题标题】:async await not working with Node.js gdrive API v3异步等待不适用于 Node.js gdrive API v3
【发布时间】:2018-05-04 00:32:46
【问题描述】:

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

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

【问题讨论】:

  • 尝试将其包装在 try/catch 中并记录 err
  • 您在第一个示例中使用了drive.files.list,在等待示例中使用了service.files.list
  • 好的,googleapis npm 安装有些奇怪。我重新安装了它,我现在正在注销我的文件。耶!

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


【解决方案1】:

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

【讨论】:

  • 这行得通,而且非常奇怪。在没有 async/await 的情况下首次运行是否会改变 node_modules 本身的某些内容?
  • 天哪,谢谢你。我只是盲目地按照谷歌自己的documentation 的说明npm install googleapis@27 --save。您的回答让我意识到我只需要更新版本的 googleapis。
猜你喜欢
  • 2021-08-03
  • 1970-01-01
  • 1970-01-01
  • 2018-06-22
  • 1970-01-01
  • 2019-01-13
  • 2021-03-26
  • 1970-01-01
  • 2017-05-11
相关资源
最近更新 更多