因此,我是javascript新手,而且我很确定代码不是理想的代码。我遇到了一些从Firestore获取数据的问题。
personalMessage函数大约需要50秒钟才能完成,我不知道为什么要花这么长时间。 此代码迅速将在1000毫秒内从数据库返回。
还建议使用任何代码风格的指针。
function sendMessageToDevice(token, payload, options) {
admin.messaging().sendToDevice(token, payload, options)
.then(response => {
console.log('Successfully sent message:', response, response.results[0].error);
return response
})
.catch(error => console.log('Error sending message:', error));
}
function getUser(userId) {
return admin.firestore().collection('users').doc(userId).get()
.then(snapshot => {
if (!snapshot.exists) {
console.log('No such document!');
return null;
}
return snapshot.data()
})
.catch(err => {
console.log('Error getting document', err);
return err;
});
}
exports.personalMessage = functions.firestore
.document('/messages/{id}')
.onCreate((snapshot, context) => {
var messageData = snapshot.data();
var userId = messageData.user;
var fromId = messageData.from;
Promise.all([getUser(userId), getUser(fromId)])
.then(([dataA, dataB]) => {
console.log(dataA.fcmToken, dataB.name);
var payload = {
notification: {
title: dataB.name + ' messaged you.',
body: 'Go check it out it',
clickAction: 'NEW_PERSONAL_MESSAGE'},
data: {
messageId: context.params.id}
};
var options = {
contentAvailable: false,
priority: 'high'
}
return sendMessageToDevice(dataA.fcmToken, payload, options);
})
.catch(error => console.log('Error sending message:', error));
return Promise.resolve('success');
});
答案 0 :(得分:1)
当道格谈论错误的诺言时。我对您的代码进行了一些更改。 但是,由于某些原因,例如网络,...
,消息可能不会立即发出。function sendMessageToDevice(token, payload, options) {
return admin.messaging().sendToDevice(token, payload, options)
}
function getUser(userId) {
return admin.firestore().collection('users').doc(userId).get()
}
exports.personalMessage = functions.firestore
.document('/messages/{id}')
.onCreate((snapshot, context) => {
var messageData = snapshot.data();
var userId = messageData.user;
var fromId = messageData.from;
return Promise.all([getUser(userId), getUser(fromId)])
.then(result=> {
if (!result[0].exists || !result[1].exists) {
console.log('No such document!');
return null;
}
return [result[0].data(),result[1].data()]
})
.then(([dataA, dataB]) => {
console.log(dataA.fcmToken, dataB.name);
var payload = {
notification: {
title: dataB.name + ' messaged you.',
body: 'Go check it out it',
clickAction: 'NEW_PERSONAL_MESSAGE'},
data: {
messageId: context.params.id}
};
var options = {
contentAvailable: false,
priority: 'high'
}
return sendMessageToDevice(dataA.fcmToken, payload, options);
})
.then(response => {
console.log('Successfully sent message:', response,
response.results[0].error);
return Promise.resolve('success');
})
.catch(error => console.log('Error sending message:', error));
});