0

I'm beginner in nodejs, This function returns "Promise {pending} " I Appreciate any help. Thanks

async function getCurrentUser(id){
try{
    let user = User.findOne({id:id})
    return user;

}catch(err){
    return err;
}     
}
Bahram Ahady
  • 29
  • 10
  • 1
    await missing?? – matcheek Aug 26 '20 at 06:52
  • Does this answer your question? [Why is my asynchronous function returning Promise { } instead of a value?](https://stackoverflow.com/questions/38884522/why-is-my-asynchronous-function-returning-promise-pending-instead-of-a-val) – jonrsharpe Aug 26 '20 at 06:53
  • where should I place the await? – Bahram Ahady Aug 26 '20 at 06:54
  • All `async` function return a promise - always. The caller must use `.then()` or `await` on that promise to get the value out of the promise. You can NEVER directly return a value from the function that was obtained asynchronously in Javascript. It cannot be done. Once it is asynchronous, all callers that want access to the value must use asynchronous means for getting access to the value. That's how asynchronous stuff works in Javascript. `await` can make some things easier, but even if you `await User.findOne()`, the caller of `getCurrentUser()` will STILL have to `.then()` or `await`. – jfriend00 Aug 26 '20 at 07:11

2 Answers2

4

You missing the await in front of some function that return a Promise

 let user = await User.findOne({id:id})

Promise is an immutable async operation that need time to finish so you either use async/await like you did or chain the promise with .then call like

User.findOne({ id })
.then((response) => {
  // do sth with the resposne
});

recommend you to read Async & Performance from YDKJS series

full rewrite of code:

async function getCurrentUser(id) {
    try {
        let user = await User.findOne({ id: id })
        return user;

    } catch (err) {
        return err;
    }
}

//  getCurrentUser usage

async function doSth(){
    let user = await getCurrentUser();
}

usage clarification:

putting async in front of a function make this function return type a promise no matter what you return inside it so the only two way to use such a function is just like how you use a promise either use it in another async function using await or use .then() chaining function

Louay Al-osh
  • 3,177
  • 15
  • 28
2

u missing await

async function getCurrentUser(id){
try{
    let user = await User.findOne({id:id})
    return user;

}catch(err){
    return err;
}     
chenc
  • 331
  • 1
  • 5