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;
}
}
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;
}
}
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
u missing await
async function getCurrentUser(id){
try{
let user = await User.findOne({id:id})
return user;
}catch(err){
return err;
}