0

I am beginner to nodejs, angularjs and firebase world. I am trying to load data into firebase but having issue because of async nature of nodejs. My purpose is to search the existing list from firebase, if some data is there than add new element to that list and write it back to firebase. Below is my code but the issue that I am facing is little weird. It works fine and keep adding data to the array until I close that node server which is running. Once i restart that node server, because of async nature of nodejs, it add new element to array first before it gets array data from firebase.

My question is, how do we restrict that to happen? I basically wants to get the array that is stored under firebase and add one value to it on the firebase. I am trying to return this data that we receive from firebase as output of the expressjs API.

We can consider this firebase as some WS API also which get us data and insert data as well.

Please help.

var ref = new Firebase('FIREBASE URL/'+req.query.id);   
var list = [];      
ref.on('value', function(snap) { list = snap.val();});
list.push(req.query.searchtext);
ref.set(list);

var result = {key: req.query.id, mainList: list};
res.json(result);

1 Answer 1

1

The "trick" is to put the dependent operation inside the callback. So instead of saying "first get the value, then add the search text, then return a JSON response", reframe it to "when we get the value, add the search text and return a JSON response".

var ref = new Firebase('FIREBASE URL/'+req.query.id);   
ref.once('value', function(snap) { 
    var list = snap.val();
    list.push(req.query.searchtext);
    ref.set(list);

    var result = {key: req.query.id, mainList: list};
    res.json(result);
});

Note that I changed from on() to once(), because I fear you're triggering an infinite loop there. If that's not the case, feel free to change it back of course.

Sign up to request clarification or add additional context in comments.

2 Comments

This works very well. Thank you so much. I did tried this approach earlier to add everything inside callback but as you just mentioned, it was going on infinite loop because of on() but I changed it to once() and it works fine now. Thank you very much again.
Another thing to consider: this code will pull down the array, add the search text and write the entire array back. This is extremely inefficient. You should check out Firebase's documentation on why we recommend against using arrays. firebase.com/docs/rest/guide/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.