2

I would like to convert the following callback procedure to a promise. I have the following:

app.get('/api/books', function(req, res)
{
  let booksCallback = function(books)
  {
    res.send(books)
  }
  DataBase.getBooks(booksCallback)

})

And then:

getBooks : function(booksCallback)
{
  database.ref('/books/').once('value', function(datasnapshot)
  {
    var books = datasnapshot.val()
    booksCallback(books)

  });
}

So I'm sending the callback function as a parameter to the function getBooks, which does an async call to Firebase. But is there any way I could do something like Database.getBooks().then(res.send(books))? But then I would need the variable books returned from the async function in getBooks first. Can this be done with a Promise?

matisetorm
  • 857
  • 8
  • 21
JuliusvM
  • 335
  • 6
  • 16

1 Answers1

4

Just return a promise from your getBooks function.

getBooks : function()
{
    return new Promise((resolve, reject) => {
        database.ref('/books/').on('value', (datasnapshot) => { 
            var books = datasnapshot.val(); 
            books ? resolve(books) : reject();
        });
    });  
}

And you can use it, in this way...

app.get('/api/books', function(req, res)
{  
  DataBase.getBooks()
   .then((books) => res.send(books))
   .catch(() => console.log('!!. ERROR'));
})
F.bernal
  • 2,594
  • 2
  • 22
  • 27
  • Great, the catch you put on res.send(), does it print the error message if the send failed, or if the books variable is null? – JuliusvM Feb 28 '18 at 13:10
  • 1
    the catch it not set in res.send is in this way... then().catch()... but if res.send fails the console log will be shown, and also if getBooks() rejects the promise. – F.bernal Feb 28 '18 at 13:14
  • 1
    @JuliusvM Both. If you want to handle only the rejection from `getBooks`, then use [`.then(…, …)` instead of `.then(…).catch(…)`](https://stackoverflow.com/q/24662289/1048572) – Bergi Feb 28 '18 at 15:29