unnamed-bull
unnamed-bull

Reputation: 361

sync way of using promises in nodejs

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

Upvotes: 1

Views: 2946

Answers (5)

Thavaprakash Swaminathan
Thavaprakash Swaminathan

Reputation: 6996

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

Upvotes: 0

shafrianadhi
shafrianadhi

Reputation: 672

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.

Upvotes: 0

Nijikokun
Nijikokun

Reputation: 1524

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 :)!

Upvotes: 1

codemax
codemax

Reputation: 1352

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

Upvotes: 1

see sharper
see sharper

Reputation: 12055

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.

Upvotes: 1

Related Questions