2017-05-09 42 views
1

我試圖異步運行一個函數,但它會引發錯誤。下面是我的代碼:(..)。然後是不是函數,firebase雲功能

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; 
} 

雖然在執行它拋出exceprtion:

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) 

我曾嘗試多種解決方案,但沒有用。這裏有人可以指出我正在犯什麼錯誤嗎?或者如果有其他解決方案?

回答

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){}) 塊內執行字符串處理。

+0

您也可以減少承諾 – Bergur

+0

謝謝,這真的很有幫助。 –

0

你不能返回一個函數,你需要返回一個事件或沒有。

+0

我已經嘗試刪除'返回',但問題是一樣的。 –