0

How can I get a return after I loop through all my firebase results to properly finish my cloud function?

var count = 0;
return ref.child('/records').once('value').then(snap=>{
    snap.forEach(snapChild=>{
        var ucName = ${snapChild.val().name.toUpperCase();
        var update = {'name':ucName);
        ref.child(`/records/${snapChild.key}`).update(update).then(()=>{
            count++;
            res.write(`<p>${ucName} updated</p>`);
        });
    })
}).then(()=>{
    return res.end(`<p>end of list (${count} records)</p>`);
})

It actually does what it is supposed to do but the counter stays at 0 and I get an error 'write after end' - I guess due to the missing return from forEach.

3
  • I have a question unrelated to your problem @alexmac answered that. Why use ES6 (fat arrow) but do not use const and let ? Commented Sep 22, 2017 at 11:40
  • You are right - I should have for ucName and update - no doubt. Just not so clear about count - as it is not 'constant'; I need to read up on it after I am 'finished' with firebase, cloud functions, node, nodemailer, handlebars, auth, Polymer, PWA.... ;) Commented Sep 22, 2017 at 21:22
  • count is a variable that is changing of value due to count++, it is a let. ucName and update in other hand do not get modified, they are const. Good luck with theses techs :) Commented Sep 22, 2017 at 22:59

1 Answer 1

1

It's because the last then callback is called, when snap children is not processed. You need to use Array#map to produce an array of promises, and Promise.all to wait until all promises are not resolved:

var count = 0;
return ref
  .child('/records').once('value')
  .then(snap => {
    let ops = snap.map(snapChild => {
        var ucName = ${snapChild.val().name.toUpperCase();
        var update = {'name':ucName);
        return ref.child(`/records/${snapChild.key}`).update(update).then(() => {
            count++;
            res.write(`<p>${ucName} updated</p>`);
        });
    });
    return Promise.all(ops);
  })
  .then(()=>{
    return res.end(`<p>end of list (${count} records)</p>`);
  });
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks - I was on the path of Promise.all but did not figure it out. Thanks for the solution.

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.