LoginSignup
3
2

More than 3 years have passed since last update.

(Firebaseの)Cloud Functionsで外部API呼び出しが時々失敗する場合はPromiseを返しているか疑え

Posted at

どんな問題?

Firebaseで、特定のFirestore Collection に Documentが追加されたら
複数のユーザにSendGrid経由でメールを送る処理を書いていた。

雑にコードを示すとこんな感じ


const functions = require('firebase-functions');

exports.sendEmailViaSendGrid = functions.region(functions.config().region.name).firestore.document("foo/{fooId}").onCreate(snapshot => {

    //メール送信対象のメアド一覧を取得
    const mailAddresses = []; 

    //各メールアドレスに対して、SendGrid API叩いてメール送る
    mailAddresses.forEach(mailAddress => {
        // 各メールアドレスに対して、SendGrid API叩く処理
    });
});

ところが、これをデプロイしたところ、
メールが送られたり送られなかったりする現象が発生した。
(全件送信されるときもあれば、数件送信できてないときもあれば、全く送信できない場合もあった)

解決方法

まさにこれでした。

以下のように修正。(これも実際のコードではなく、雑に概念だけ書いたもの)


const functions = require('firebase-functions');

exports.sendEmailViaSendGrid = functions.region(functions.config().region.name).firestore.document("foo/{fooId}").onCreate(snapshot => {

    //メール送信対象のメアド一覧を取得
    const mailAddresses = []; 

    //各メールアドレスに対して、SendGrid API叩いてメール送る
    return Promise.all(mailAddresses.map(mailAddress => {
        // 各メールアドレスに対して、SendGrid API叩く処理(Promiseを返す)
    }));
});

ちゃんと全件にメールが飛ぶようになりました。

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