facebook twitter hatena line email

「Gcp/Firebase/Firestore/async」の版間の差分

提供: 初心者エンジニアの簡易メモ
移動: 案内検索
行2: 行2:
  
 
==asyncを使わないパターン==
 
==asyncを使わないパターン==
 +
<pre>
 
const functions = require('firebase-functions');
 
const functions = require('firebase-functions');
 
const admin = require('firebase-admin');
 
const admin = require('firebase-admin');
行19: 行20:
 
   });
 
   });
 
});
 
});
 +
</pre>
 +
 +
==asyncを使うパターン==
 +
<pre>
 +
exports.dbasync = functions
 +
  .region('asia-northeast1')
 +
  .https.onRequest(async(request, response) => {
 +
      var snapshot = await admin.firestore().collection('scores')
 +
        .orderBy('maxKanaSpeed', 'desc')
 +
        .limit(50)
 +
        .get();
 +
      var scores = snapshot.docs.map(x => x.data());
 +
      var json = JSON.stringify(scores);
 +
      response.send("json" + json);
 +
});
 +
</pre>

2019年8月12日 (月) 21:39時点における版

firestoreをasyncを使って取得する

asyncを使わないパターン

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.db = functions
  .region('asia-northeast1')
  .https.onRequest((request, response) => {
  admin.firestore().collection('scores')
        .orderBy('maxKanaSpeed', 'desc')
        .limit(50)
        .get()
        .then((snapshot) =>
      {
        var scores = snapshot.docs.map(x => x.data());
        var json = JSON.stringify(scores);
        response.send("json" + json);
  });
});

asyncを使うパターン

exports.dbasync = functions
  .region('asia-northeast1')
  .https.onRequest(async(request, response) => {
      var snapshot = await admin.firestore().collection('scores')
        .orderBy('maxKanaSpeed', 'desc')
        .limit(50)
        .get();
      var scores = snapshot.docs.map(x => x.data());
      var json = JSON.stringify(scores);
      response.send("json" + json);
});