Async/await javascript

Asked

Viewed 191 times

2

How can I make the code below less messy with asnyc/await?

class Backend {
   getUsers(callback){
      const database = firebase.database().ref('users/')
      const onReceive = (data) => {
          callback({
             data
          )}
      }
      database.on('child_added', onReceive)
   }
}

Backend.getUsers((data) => {
   console.log(data)
   // Coloquei o console.log() só por colocar mesmo
})
  • You would like to load all users at once or get "listening" to each user entered?

1 answer

5

First you will have to create a static method to be able to access it without creating an instance of Backend using static.

Now to use await you will need to use files. You could use the modifier async in its method to transform the return of getUsers in a resolution of a file, but as the value to be returned is inside a callback (onReceive), there is no way you can return the value with the declaration return. You will have to resort to creating an object Promise so you can use the callbacks resolve or reject inside the callback of database.on.

class Backend {
   static getUsers() {
      return new Promise((resolve, reject) => {
          const database = firebase.database().ref('users/')
          database.on('child_added', data => resolve({ data }))
      })
   }
}

async function imprimirUsers() {
    const data = await Backend.getUsers()
    console.log(data)
}

imprimirUsers()
  • An additional would be to add one try/catch to capture errors, if you have: Following example: https://jsbin.com/jeyabikoqo/edit?js

  • Somehow only returning 1 user

  • This solution using Promise does not work, since the callback is called multiple times, one for each node added (child_added). This helps to understand what happens: http://jsbin.com/gemepay/3/edit?js,console

Browser other questions tagged

You are not signed in. Login or sign up in order to post.