2017-05-09 19 views
1

私は非同期的に関数を実行しようとしていますが、エラーをスローします。私は複数のソリューションが、使用のどれを試してみました(..)。次に関数ではありません、firebase cloud関数

TypeError: getSenderIds(...).then is not a function 
    at exports.listenForNotificationRequests.functions.database.ref.onWrite.event (/user_code/index.js:20:39) 
    at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:35:20 
    at process._tickDomainCallback (internal/process/next_tick.js:129:7) 

:実行時に、それはexceprtionスロー

exports.listenForNotificationRequests = functions.database.ref('/notificationRequests/{pushId}') 
    .onWrite(event => { 
     const requestId = event.data.val(); 
     var sentTo = requestId.sentTo; 
     var senderIds = sentTo.split(","); 
    // var senderTokens = ""; 

     var payload = { 
       data: { 
        title: requestId.username, 
        message: requestId.message, 
        sentFrom: requestId.sentFrom 
       } 
     }; 

     getSenderIds(senderIds).then(function(senderTokens){ 
      console.log("SenderTokens", senderTokens); 
      admin.messaging().sendToDevice(senderTokens.split(","), payload) 
        .then(function(response) { 
         console.log("Successfully sent message:", response); 
        }) 
        .catch(function(error) { 
         console.log("Error sending message:", error); 
      }); 

     }); 

}); 

function getSenderIds(senderIds){ 
    var senderTokens = ""; 
    senderIds.forEach(function (snapshot){ 
       var ref = admin.database().ref("users/"+snapshot+"/token"); 
       console.log("refernce", snapshot); 
       ref.once("value", function(querySnapshot2) { 
         var snapVal = querySnapshot2.val(); 
         console.log("Token", snapVal); 
         senderTokens = senderTokens+","+snapVal; 
       }); 
    }); 
    return senderTokens; 
} 

中:以下は私のコードです。私が作っている間違いを指摘できる人は誰ですか?またはこれに他の解決策がある場合は?

答えて

0

then()を使用するには、getSenderIds()は現在のところ文字列を返す間にPromiseを返す必要があります。

ref.once()はPromiseを返します。あなたができることは、senderTokensを配列にし、繰り返しごとにref.once()をこの配列にプッシュすることです。

ref.once()がPromiseを返すので、senderTokensは各クエリの結果を含むPromisesの配列になります。 Promise.all(senderTokens)read more about Promise.all hereを返すことができます。

次に、senderTokens配列の各項目で.val()を呼び出して、then(function(senderTokens){}) ブロック内のtoString処理を行います。

+0

あなたはまた、約束を減らすことができました – Bergur

+0

ありがとう、本当に役に立ちました。 –

0

関数を返すことはできません。イベントを返すか何も返す必要はありません。

+0

私は 'return'を削除しようとしましたが、問題は同じです。 –

関連する問題