简体   繁体   中英

Function returns a pending promise, but value of variable is returned into it

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

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);
})()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM