![](/img/trans.png)
[英]Error on deploy Firebase cloud function Each then() should return a value or throw
[英]Each then() should return a value or throw Firebase cloud functions
我正在使用 javascript 為 firebase 編寫一個雲函數,但我被卡住了,我不知道錯誤的確切含義並且無法解決它..錯誤狀態:27:65 錯誤每個 then() 應該返回一個值或拋出承諾/總是回報
'use strict'
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.sendNotification = functions.database.ref('/notifications/{user_id}/{notification_id}').onWrite((change, context) => {
const user_id = context.params.user_id;
const notification_id = context.params.notification_id;
console.log('We have a notification from : ', user_id);
if (!change.after.val()) {
return console.log('A Notification has been deleted from the database : ', notification_id);
}
const deviceToken = admin.database().ref(`/ServiceProvider/${user_id}/device_token`).once('value');
return deviceToken.then(result => {
const token_id = result.val();
const payload = {
notification: {
title : "New Friend Request",
body: "You Have Received A new Friend Request",
icon: "default"
}
};
return admin.messaging().sendToDevice(token_id, payload).then(response => {
console.log('This was the notification Feature');
});
});
});
改變這個:
return admin.messaging().sendToDevice(token_id, payload).then(response => {
console.log('This was the notification Feature');
});
對此:
return admin.messaging().sendToDevice(token_id, payload).then(response => {
console.log('This was the notification Feature');
return null; // add this line
});
then
回調只需要返回一個值。
但是,eslint 可能會在您的代碼中抱怨嵌套then()
,這也是一種反模式。 你的代碼應該更像這樣的結構:
const deviceToken = admin.database().ref(`/ServiceProvider/${user_id}/device_token`).once('value');
return deviceToken.then(result => {
// redacted stuff...
return admin.messaging().sendToDevice(token_id, payload);
}).then(() => {
console.log('This was the notification Feature');
});
請注意,每個然后相互鏈接,而不是相互嵌套。
改變這個:
return admin.messaging().sendToDevice(token_id, payload).then(response => {
console.log('This was the notification Feature');
});
進入這個:
return admin.messaging().sendToDevice(token_id, payload).then(response=>{
console.log('This was the notification Feature');
return true;
},err=>
{
throw err;
});
由於錯誤使用時,說then
你需要返回一個值。
這是jslinting告訴你,每一個.then
必須包括返回值。 換句話說,避免promise 反模式。
您可能會發現async
函數更容易理解。 請注意,您需要運行 Node 8 運行時以獲得異步支持...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.