LoginSignup
10
11

More than 3 years have passed since last update.

【GAS×Vue.js Webアプリ】google.script.run で async/await を使う

Last updated at Posted at 2019-08-30

はじめに

某デジタルメディアでGASを使ってを社内ツールを開発している情報系学部4年生です。
WebアプリケーションをVue.jsで書き、バックエンドや各種APIコールなどをGoogle Apps Scriptで処理し、データベースにスプレッドシートを使用することでインフラコスト0で運用できる。

Webアプリケーション側からGAS内のコードを走らせてその戻り値を受け取るために
google.script.run を使用すると楽に実装できるが、サーバサイドのコードを走らせているため、非同期処理となり、複数のスプレッドシートを読み込んで実装する場合はコールバック地獄が発生する。

その問題を解決できたので、簡単にメモ
参考にしたサイト

コード

フロントのVue.jsの処理を以下のように実装する。

hoge.js
let db = new Vue({
  el: '#app',
  data: {
    sheet_a: null,
    sheet_b: null,
  },
  methods: {
    loadData: async function() {
      //ここに書くと順番に実行される
      const sheet_a = await this.getSheetA();
      console.log('成功!取得したデータ: ' + JSON.stringify(sheet_a));
      this.sheet_a = sheet_a;


      const sheet_b = await this.getSheetB();
      console.log('成功!取得したデータ: ' + JSON.stringify(sheet_b));
      this.sheet_b = sheet_b;
      //全部のデータを取得した後に実行したい処理を下に記述

    },

    getSheetA: function() {
      //コード.js内のgetSheetA()を実行
      return new Promise((resolve, reject) => {
        google.script.run
          .withSuccessHandler((result) => resolve(result))
          .withFailureHandler((error) => resolve(error))
          .getSheetA();
      });
    },
    getSheetB: function() {
      //コード.js内のgetSheetB()を実行
      return new Promise((resolve, reject) => {
        google.script.run
          .withSuccessHandler((result) => resolve(result))
          .withFailureHandler((error) => resolve(error))
          .getSheetB();
      });
    }

  },
  //マウント時
  mounted: function() {
    //マウント時にシートを取得
    this.loadData();
  },
});

一応GAS側で実行されるコードも記述しておきます。
※本来はdoGet()関数内にHTMLファイルを返すためのコードを書かないといけません。
GAS×Vueで簡単なWebアプリを作る方法はこちら

コード.gs
function getSheetA() {
  var sheet = SpreadsheetApp.getActive().getSheetByName('シート1');
  var rows = sheet.getDataRange().getValues();
  var keys = rows.splice(0, 1)[0];
  return rows.map(function(row) {
    var obj = {};
    row.map(function(item, index) {
      obj[String(keys[index])] = String(item);
    });
    return obj;
  });
}

function getSheetB() {
  var sheet = SpreadsheetApp.getActive().getSheetByName('シート2');
  var rows = sheet.getDataRange().getValues();
  var keys = rows.splice(0, 1)[0];
  return rows.map(function(row) {
    var obj = {};
    row.map(function(item, index) {
      obj[String(keys[index])] = String(item);
    });
    return obj;
  });
}
10
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
11