I want to get some data from my firebase real-time database. It worked once but now returns 'Promise {pending}'
const userId = admin.database()
.ref(/dhabba_orders/{userID}
).once('value');
The above code returned the correct value once and now only returns 'Promise {pending}'
exports.notificationMake =
functions.database.ref(`/dhabba_orders/{userId}/status`)
.onWrite((change, context) => {
const userId = admin.database()
.ref(`/dhabba_orders/{userID}`).once('value');
console.log(userId);
const payload = {
notification: {
title: `Hi`,
body: `Hey`
}
};
return admin.messaging().sendToDevice(userId, payload);
});
答案 0 :(得分:0)
As you can see from the API documentation, once()
performs a query asynchronously and returns a Promise that you can use to get a DataSnapshot at the request location in the in the database. However, you're assuming that it simply returns the value directly. Instead, you'll need to make use of that Promise in order to get the user ID. Your function should look more like this:
exports.notificationMake =
functions.database.ref('/dhabba_orders/{userId}/status').onWrite((change, context) => {
admin.database().ref(`/dhabba_orders/{userID}`).once('value')
.then(snapshot => {
const userId = snapshot.data();
console.log(userId);
const payload = {
notification: {
title: `Hi`,
body: `Hey`
}
};
return admin.messaging().sendToDevice(userId, payload);
});
});
答案 1 :(得分:0)
更新:解决方案
exports.notificationMake =
functions.database.ref('/dhabba_orders/{user_uid}').onWrite((change, context) => {
let userId = context.params.user_uid;
let orderStatus = context.params.order_status;
Promise.all([userId, orderStatus]).then(others => {
console.log(userId);
console.log(orderStatus);
const payload = {
notification: {
title: `Order Accepted!`
}
};
admin.messaging().sendToDevice(userId, payload);
return 0;
}).catch(error => {
console.log(error);
});
return 0;
});