Using Async And Await In Nodejs Getting Promise { }
In my case , i am able to get the token but not the way i wanted ie i do not want to print promise pending and my output after running in tokenDisp.js is : output: Promise { pendin
Solution 1:
All async
functions return a promise and you still have to use .then()
or await
on the return value from the async
function in order to use that. If you return a value from your async
function, it will be the resolved value of the returned promise. If you throw an exception, the exception will be the reason for the rejection of the returned promise.
The use of await
inside the function is a convenience INSIDE the async function. It does not magically make an asychronous operation into a synchronous one. So, your function returns a promise. To get the value out of it, use .then()
on it.
module.exports = async functiondoLogin() {
const token = await loginToken();
const myToken = JSON.parse(token);
console.log(myToken);
return myToken; // this will be resolved value of returned promise
};
const myToken = require('./login.js);
myToken().then(token => {
// got token here
}).catch(err => {
console.log(err);
});
Note: your login.js module produces the same result as if it was written like this (without using async
or await
):
module.exports = functiondoLogin() {
returnloginToken().then(token => {
const myToken = JSON.parse(token);
console.log(myToken);
return myToken; // this will be resolved value of returned promise
});
};
Post a Comment for "Using Async And Await In Nodejs Getting Promise { }"