This question already has answers here:
How do I convert an existing callback API to promises?
                                
                                    (20个答案)
                                
                        
                                去年关闭。
            
                    
我想将以下回调过程转换为Promise。我有以下几点:

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

})


接着:

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

  });
}


因此,我将回调函数作为参数发送给函数getBooks,该函数会对Firebase进行异步调用。但是有什么办法可以做Database.getBooks().then(res.send(books))之类的事情吗?但是然后我首先需要从getBooks中的async函数返回的变量本。可以用承诺来做到吗?

最佳答案

只需从getBooks函数返回一个Promise。

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


您可以通过这种方式使用它...

app.get('/api/books', function(req, res)
{
  DataBase.getBooks()
   .then((books) => res.send(books))
   .catch(() => console.log('!!. ERROR'));
})

09-18 15:26