-1

This is the code

function readNotes(){
  return new Promise((resolve, reject) => {
     user = firebase.auth().currentUser.uid
     ref = database.ref("users/" + user + "/notes")
     ref.get().then( function(snapshot) {
         if (snapshot.exists()) {
              keys= Object.keys(snapshot.val())
              console.log(keys)
             resolve(keys);
         } else {
             console.log("No data available");
         }
     }).catch((error) => {
         reject(error);
     })
  })
}type here

I tried calling the function in the console and I was expecting for it to return a fulfilled promise, especially because I was able to log the value of the keys variable

  • Avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! – Bergi Jan 07 '23 at 08:00
  • "*I was expecting for it to return a fulfilled promise*" - no, it's returning a promise that will **later** fulfill, after it also has logged the `keys` variable – Bergi Jan 07 '23 at 08:01

1 Answers1

0

Your function returns Promise. (hence return new Promise(...) at the beginning of your function);

You will need to either await (if you are inside an async function) like so:

const notes = await readNotes();
console.log(notes);

or you can use .then() like so:

readNotes().then(notes => {
    console.log(notes)
}).catch(err => {
    console.error(error);
}

Note: do not forget .catch to intercept errors.

If you are not in async function, but want to use async/await you can use an IIFE (Immediately Invoked Function Expression).

(async () => {
    const notes = await readNotes();
    console.log(notes);
})()
Alex Kolarski
  • 3,255
  • 1
  • 25
  • 35