Reputation: 13
I want to upload data to Firebase's Real-time Database. This information is relative to user's ID. I have downloaded this relevant user information in a JSON file. I can read this information to the Node.js command prompt easily using JavaScript.
I know how to push and set data using JavaScript as well.
My issue seems to be including both this read from a file operation and this write to firebase operation in the same JavaScript code.
To test this I wrote a really basic JavaScript program that uses a call back function so I can make sure that it finishes reading from the file before anything starts writing but even writing the commented out codes makes the whole JavaScript program not work. (I know that I do not need BOTH the first 2 lines, but I was trying different things and I wanted to show them both)
function GetAllData(callback) {
//var userData = require('./save_file.json');
// var fs = require('fs')
// var obj = JSON.parse(fs.readFileSync('save_file.json').toString())
var a=2;
if (typeof callback === 'function') {
callback();
}
}
function PushData() {
var config = {
apiKey: ,
authDomain: ,
databaseURL: ,
projectId: ,
storageBucket: ,
messagingSenderId:
};
// Initialize your Firebase app
firebase.initializeApp(config);
// Reference to your entire Firebase database
var myFirebase = firebase.database().ref();
var recommendations = myFirebase.child("recommendations");
setTimeout(pushStuff(), 500);
function pushStuff(){
recommendations.set({
"title": "nn"
});
}
};
//}
GetAllData(PushData);
If I remove the commented out code in the first section, "nn" is written just fine. At this point I just want to be able to READ and WRITE in the same code :(
Upvotes: 0
Views: 1687
Reputation: 83103
As you mention in your question, read and write calls to the Firebase database are asynchronous.
They return promises, as you can see here or here, from the Firebase documentation.
You therefore have to chain these promises like for example, in the case of a read followed by a write:
return firebase.database().ref('/users/' + userId).once('value')
.then(snapshot => {
var username = (snapshot.val() && snapshot.val().username) || 'Anonymous';
return firebase.database().ref(....).set({ username: username });
})
.then(() => {
console.log('Operation succeeded');
})
.catch(error => {
console.log('Operation failed');
});
Also, have a look a this SO post Reading a nodejs promise with firebase
Upvotes: 1