Search code examples
node.jsfirebasees6-promise

How to refactor Firebase promise to return a to another (.then) but outside the function scope?


Here is the code I have so far:

This is promise 1:

const promise1 = () => new Promise((resolve) => {

console.log("1");
resolve(["hi", "world"]);

})

This is promise 2:

const promise2 = (data) => {

console.log("2");

ref.ref("server/events").once("value").then(function (snapshot) {


  console.log(inside firebase ref');
     
      return Promise.resolve("test");
  }
 })
 }

This is promise 3:

const promise3 = (value) => {
console.log(" 3 ");
console.log(value)

}

and to call 3 of them:

 promise1()
.then((value) => promise2(value))
.then((value) => promise3(value));

And the output is:

1

2

3

undefined

inside firebase ref


Solution

  • Your question isn't super clear, but I think you are unhappy that promise3 logs out an undefined instead of the value you would hope to be returned from promise2. And that the firebase callback seems to happening out of order.

    Problem is, you never return a promise from the promise2 function, so:

    ref.ref("server/events").once("value").then(function (snapshot) {...
    

    needs to be

    return ref.ref("server/events").once("value").then(function (snapshot) {...
    

    Pro tip, you can invoke that promise chain in a "point free" fashion:

    promise1()
    .then(promise2)
    .then(promise3);