LoginSignup
2
1

More than 3 years have passed since last update.

【Node.js】google-spreadsheet-npmにおける同期処理について

Last updated at Posted at 2019-03-13

前回の続きで、SpreadSheetから取得した値を格納した変数を別の関数内で使おうと思ったらつまづいた
Node.jsでGoogleSpreadSheetから値を取得する

別の関数内でグローバルに変数を使う

例えば、この取得関数内だけではなく別関数内でも変数を受け渡したい場合に、JSの特性上、JavaScript以外(例えばデータベース等)に仕事を任せてる間、その処理を待たないで次へ進めるので同期処理にしないと変数に格納されないまま処理が実行される場合がある。

詳しく知りたい人は先人の知恵を借りよう。
JavaScriptの同期、非同期、コールバック、プロミス辺りを整理してみる

なので、格納した変数をグローバルに使いたい場合はasyncPromiseを使って同期処理になるようにしなければならない。

サンプルコード(Promise ver.)

index.js
//パッケージを読み込む
var GoogleSpreadsheet = require('google-spreadsheet');

//必要情報の格納
var test_sheet = new GoogleSpreadsheet('<spreadsheet key>');
var credentials = require('./上記参考サイト内の連携処理でインストールしたファイル名(拡張子は .json) ');

//データ格納用配列の用意
var array =[];

//関数実行順宣言
get_function()
.then(use_function)
.then((response) => {
  console.log("all done!");
});

//データ取得関数
function get_function(){
  return new Promise((resolve,reject) => {
    test_sheet.useServiceAccountAuth(credentials, function(err){
      //sheetデータの取得
      test_sheet.getInfo(function(err, data){
      sheet = data;
      //取得したsheetの中に自分の取得したいシート名があるかチェック
      for(var i in sheet.worksheets) {
        if(sheet.worksheets[i].title === 'シート名') {
          sheet.worksheets[i].getRows(function(err, rows) {
            for(var i in rows) {
              array.pushrows[i].欲しい情報のカラム名;
            };
            resolve();
          });
        };
      };
    });
  });
};

//取得データ使用関数
function use_function(passVal){
  return new Promise((resolve,reject) => {
    console.log(array);
  };
  resolve();
};

Node.jsってやっぱり楽しい。

2
1
1

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
2
1