Не может уничтожить ошибку свойства - googleapi - PullRequest
0 голосов
/ 28 мая 2018

Ошибка при использовании googleapi

Моя ошибка:

(узел: 7776) UnhandledPromiseRejectionWarning: TypeError: Невозможно уничтожить свойство data из 'undefined' или 'null'.на gmail.users.labels.list

меня сбивает с толку то, что все работает, распечатывает это так, как должно, но почему выдает ошибку об отсутствии значения, если это явно не так?как это можно решить?

Это мой код:

var async = require('async-kit');
const fs = require('fs');
const readline = require('readline');
const {
  google
} = require('googleapis');

const SCOPES = ['https://www.googleapis.com/auth/gmail.readonly'];
const TOKEN_PATH = 'credentials.json';

function test(methodname) {
  console.log('called');
  fs.readFile('client_secret.json', (err, content) => {
    if (err) return console.log('Error loading client secret file:', err);
    // Authorize a client with credentials, then call the Google Sheets API.
    authorize(JSON.parse(content), methodname);
  });
}

/**
 * Create an OAuth2 client with the given credentials, and then execute the
 * given callback function.
 * @param {Object} credentials The authorization client credentials.
 * @param {function} callback The callback to call with the authorized client.
 */
function authorize(credentials, callback) {
  console.log('authorized');
  const {
    client_secret,
    client_id,
    redirect_uris
  } = credentials.installed;
  const oAuth2Client = new google.auth.OAuth2(
    client_id, client_secret, redirect_uris[0]);

  // Check if we have previously stored a token.
  fs.readFile(TOKEN_PATH, (err, token) => {
    if (err) return getNewToken(oAuth2Client, callback);
    oAuth2Client.setCredentials(JSON.parse(token));
    callback(oAuth2Client);
  });
}

/**
 * Get and store new token after prompting for user authorization, and then
 * execute the given callback with the authorized OAuth2 client.
 * @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
 * @param {getEventsCallback} callback The callback for the authorized client.
 */
function getNewToken(oAuth2Client, callback) {
  const authUrl = oAuth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES,
  });
  console.log('Authorize this app by visiting this url:', authUrl);
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
  });
  rl.question('Enter the code from that page here: ', (code) => {
    rl.close();
    oAuth2Client.getToken(code, (err, token) => {
      if (err) return callback(err);
      oAuth2Client.setCredentials(token);
      // Store the token to disk for later program executions
      fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
        if (err) return console.error(err);
        console.log('Token stored to', TOKEN_PATH);
      });
      callback(oAuth2Client);
    });
  });
}

/**
 * Lists the labels in the user's account.
 *
 * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
 */
function listLabels(auth, callback) {
  const gmail = google.gmail({
    version: 'v1',
    auth
  });
  gmail.users.labels.list({
    userId: 'me',
  }, (err, {
    data
  }) => {
    if (err) {
      console.log('The API returned an error: ' + err);
      callback();
    }
    const labels = data.labels;
    console.log('got labels');
    if (labels.length) {
      interimlabels = labels;
      interimlabels.forEach((label) => {
        console.log(`- ${label.name}`);
      });
      callback();
    }
    else {
      console.log('No labels found.');
      callback();
    }
  });
}
var interimlabels = [];
async.series([
    function getStuff(callback) {
      test(listLabels);
      if (interimlabels.length != 0) {
        console.log('labels', interimlabels);
        callback();
      }
    }
  ])
  .exec(function(error, results) {
    if (error) {
      console.log('shit');
    }
    else {
      console.log('done');
    }
  });

Редактировать: я просто хочу добавить, что он работает идеально, выходит из системы, как и должно, но после того, как он дает мне ошибкув конце edit2: хорошо, так что если я удалю callback ();из списка Labels ();тогда отклонение обещания исчезнет, ​​но тогда код, очевидно, будет зависать, так в чем же может быть проблема с обратным вызовом?

1 Ответ

0 голосов
/ 28 мая 2018

// Вы получаете ошибку, и у вас есть ошибка в обработке ошибки.Вы уничтожили результат из Google API.Но на самом деле вы не получили никакого результата, поэтому он показывал данную ошибку: Cannot destructure propery error - googleapi

// Попробуйте этот код.

/**
 * Lists the labels in the user's account.
 *
 * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
 */
function listLabels(auth, callback) {
  const gmail = google.gmail({
    version: 'v1',
    auth
  });
  gmail.users.labels.list({
    userId: 'me',
  }, (err, result) => {
    if (err || !result) {
      console.log('The API returned an error: ' + err);
      callback();
    } else {
      const labels = result.data.labels;
      console.log('got labels');
      if (labels.length) {
        interimlabels = labels;
        interimlabels.forEach((label) => {
          console.log(`- ${label.name}`);
        });
        callback();
      }
      else {
        console.log('No labels found.');
        callback();
      }
    }
  });
}

Надеюсь, это решит ваш запрос.

Обновленный код:

function listLabels(auth, callback) {
  const gmail = google.gmail({
    version: 'v1',
    auth
  });

  var request = gmail.users.labels.list({
    'userId': 'me'
  });
  request.execute(function(resp) {
    console.log("resp", resp);
    var labels = resp.labels;
    callback(labels);
  });
}
...