【发布时间】:2020-02-16 16:43:06
【问题描述】:
我对 Node JS 还很陌生,所以我有点挣扎。
我正在尝试使用他们的 API 从我的 Node Js 代码中读取 google drive 的文件。
我有以下代码
router.get('/', function (req, res, next) {
var pageToken = null;
// Using the NPM module 'async'
async.doWhilst(function (callback) {
drive.files.list({
q: "mimeType='image/jpeg'",
fields: 'nextPageToken, files(id, name)',
spaces: 'drive',
pageToken: pageToken
}, function (err, res) {
if (err) {
// Handle error
console.error(err);
callback(err)
} else {
res.files.forEach(function (file) {
console.log('Found file: ', file.name, file.id);
});
pageToken = res.nextPageToken;
callback();
}
});
}, function () {
return !!pageToken;
}, function (err) {
if (err) {
// Handle error
console.error(err);
} else {
// All pages fetched
}
})
res.render('index', { title: 'Express' });
});
当我发送获取请求时,上面的代码给了我以下错误
(node:13884) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'forEach' of undefined
at E:\nodejs\newcelebapi\routes\index.js:49:17
at E:\nodejs\newcelebapi\node_modules\googleapis-common\build\src\apirequest.js:43:53
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:13884) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:13884) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
问题出在下面一行
res.files.forEach(function (file) {
我已尽我所能,放弃理解问题。
你能帮我解决这个问题吗?
谢谢!
【问题讨论】:
-
JS 在编写
async包后继续前进,并且它已经支持 promises 和原生 async/await 有一段时间了 - 我强烈建议不要使用该包,除非你对 JS 有足够的了解,能够解释为什么原生 async/await 或 Promise 不够好(可以肯定地说,现在情况并非如此)。
标签: javascript node.js google-drive-api