1

loginTest() gives me resolve(value) so it goes to .then , my problem is since promise is async code, console.log(token) gets printed with promise-pending before promise fulfills.I want to display the value only after promise is fulfilled.Can any one help ?

 const token = loginTest().then(res => res).catch(err => err);
 console.log(token);
unnamed-bull
  • 361
  • 4
  • 15
  • Already explained to you in your previous question: https://stackoverflow.com/questions/49267856/using-async-and-await-in-nodejs-getting-promise-pending from an hour ago. You can never get the value directly out of a promise - NEVER. You either use `await` or `.then()` to get the value. Welcome to asynchronous programming in Javascript. See the example in the accept answer to your previous question. It's all right there. – jfriend00 Mar 14 '18 at 02:45
  • It dint resolve my issue .... my usecase is i want to return token from getToken() async function which has await loginTest() too and export the module in another js file.After importing the module i am using function expression to store returned value from function to variable and printing that value gives me promise pending – unnamed-bull Mar 14 '18 at 02:47
  • You CAN'T return `token` directly - never. Your function returns before `token` is even available. You really need to read a lot more about how promises works. You can NEVER get the value directly out of a promise. You ALWAYS use `.then()` or `await`. So you can't do `var token = loginTest();` and expect it to be your value. If you do, token will just be the promise. – jfriend00 Mar 14 '18 at 02:49
  • Possible duplicate: [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call/14220323#14220323). You should really study that other answer. – jfriend00 Mar 14 '18 at 02:50
  • `loginTest().then(token => { /* you can use token here and only here */});` – jfriend00 Mar 14 '18 at 02:52
  • There is no synchronous way of using promises. – jfriend00 Mar 14 '18 at 03:17

5 Answers5

1

You could leverage Async / Await functionality:

const token = await loginTest()
console.log(token)

For Example:

async function getToken () {
  const token = await loginTest()
  console.log(token)
}

getToken()

You could also do the following for a "synchronous" promises way:

loginTest()
  .then(res => res)  // Retained for example sake of chaining promises
  .then(res => console.log(res))
  .catch(err => console.log(err))

This is assuming that token is res, adjust accordingly if it is an object and you need a child property :)!

Nijikokun
  • 1,514
  • 1
  • 15
  • 22
  • const myToken = async function () { const myTok = await loginToken(); return myTok; }; console.log(myToken()); still i m getting promise pending as output – unnamed-bull Mar 14 '18 at 02:36
  • I have updated my answer with a more verbose example, let me know if you still get the issue :) @SrikanthTunuguntla – Nijikokun Mar 14 '18 at 02:42
  • i m still getting an issue ... my usecase is i want to return token from getToken() async function which has await loginTest() too and export the module in another js file.After importing the module i am using function expression to store returned value from function to variable and printing that value gives me promise pending – unnamed-bull Mar 14 '18 at 02:46
  • Would need to see your loginTest function to be able to help further, sounds like nested promises, un-resolved promises, or improperly implemented async await, you can easily do async await through imports, but if the promises are nested or never resolved you will have issues. – Nijikokun Mar 14 '18 at 05:12
1

Try this:

loginTest().then(res => {
   console.log(res.token);
}).catch(err => err);

This presumes that the token is provided as a field of res. I don't know the structure of the response so you need to check that. Token will not be returned directly from loginTest if it is async.

see sharper
  • 11,505
  • 8
  • 46
  • 65
1

Use ES6's Async / Await.

const token = await loginTest();

But please note that this line of code needs to be wrapped in a async function. Otherwise, await will not work. And note that await cannot be used in global scope.

For example:

async function getToken() { 
  const token = await loginTest();
  // this next line will execute after the result of of loginTest() returns
  console.log(token);
  // do something with token after this line
  const mutateToken = token + '123456';
}

Documentation of Async / Await found here: Async / Await

codemax
  • 1,322
  • 10
  • 19
  • my usecase is i want to return token from getToken() async function which has await loginTest() too and export the module in another js file.After importing the module i am using function expression to store returned value from function to variable and printing that value gives me promise pending – unnamed-bull Mar 14 '18 at 02:44
  • in that case, are you handling the returned promise object with a thenable? – codemax Mar 14 '18 at 02:46
  • using thenable i get the token perfectly but i want to store it in a variable and print syncronously , the problem comes like it prints before thenable executes as thenable is asyncronous – unnamed-bull Mar 14 '18 at 02:51
  • Yes, so (1) you can edit loginTest() func to add a thenable which returns the value of the token, or (2) add the thenable in const token = await loginTest().then(token => token); – codemax Mar 14 '18 at 03:04
0

Try this promise :

var loginTest = new Promise(function 
(resolve, reject) {
    if (isLogin) {
        var login = {
            username: 'admin'
            //something that related with the loginTest..
        };
        resolve(login);
    } else {
        var reason = new Error('some errors..');
        reject(reason);
    }
})

loginTest
.then((fulfilled) => {
    console.log(fulfilled);
})
.catch((error) => {
    console.log(error.message);
})

so, loginTest will be printed after fulfilled, then catch error if there are some errors.

shafrianadhi
  • 642
  • 5
  • 8
0

You can't access token by doing like below as it is an asyn method.

 const token = loginTest().then(res => res).catch(err => err);
 console.log(token);

Instead use below

loginTest().then(res => { 
   const token = res.token;
   // your further code goes here.
}).catch(err => err);
Thavaprakash Swaminathan
  • 6,226
  • 2
  • 30
  • 31