【问题标题】:Running do while loop results in fatal error运行 do while 循环会导致致命错误
【发布时间】:2020-08-01 20:32:00
【问题描述】:

我正在尝试使用 google drive api 来获取特定文件夹中的文件列表。现在,当我尝试运行 do..while 循环以获取小块文件列表时,应用程序崩溃并出现致命错误:

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory  

片段

function listFiles(auth) {
    const drive = google.drive({ version: "v3", auth });
    let pageToken = null;

    do {
        drive.files.list({
            pageSize: 10,
            q: "'root' in parents and trashed=false",
            fields: "nextPageToken, files(id, name)",
            pageToken: pageToken,
        }, (err, res) => {
            if (err) return console.error(`The API returned an error: ${err}`);

            pageToken = res.data.nextPageToken;
            const files = res.data.files;

            if (files.length) {
                files.forEach((file) => {
                    console.log(`${file.name}  (${file.id})`);
                });
            } else {
                console.log("No files found!");
            }
        });
    }
    while(!pageToken);

AFAIK 如果没有更多文件,nextPageToken 将是未定义的。

【问题讨论】:

  • 不。我试过了,它不起作用。同样的问题。我的电脑资源也被占用了。

标签: javascript node.js google-drive-api google-api-js-client


【解决方案1】:

相信您已经听说过 JS 中的“异步”一词。显然drive.files.list 是一个回调风格的异步函数。而这个pageToken = res.data.nextPageToken 赋值发生在回调内部,这意味着pageToken 的值不会立即从null 更改为something

但是你的做法是......而逻辑是同步发生的。因此while(!pageToken) 基本上等于while(true)。这就是你得到错误的原因,你的程序陷入了无限循环。

【讨论】:

  • 是的,我确实听说过这个词。所以基本上你的建议是重写为 async/await 风格?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-05
  • 1970-01-01
  • 2022-01-21
  • 2021-07-17
相关资源
最近更新 更多