0

I have the following code.

I get the data from db inside the .then . i want to use the var data = data.get({ plain: true }) data outside the then.. how can i do this.

const datas = roleService.getRoleById(1)
      .then(data => {
        var data = data.get({ plain: true })
          console.log(data.get({ plain: true }))
        // return data.get({ plain: true })
        }
          )
      .catch((error) => res.status(400).send(error));

Thanks in advance.

Hariharan AR
  • 1,386
  • 11
  • 20
  • 3
    Possible duplicate of [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) – CertainPerformance May 31 '19 at 06:55
  • You **must** call `.then` (or use `await`) on a Promise to consume it – CertainPerformance May 31 '19 at 06:55
  • 1
    You always have to call `.then` because you don't know when the value will be ready (or if it iever). Any processing that depends on the query result must happen inside the callback(s). A promise instance is merely a handle to the next `.then` callback. Now, callbacks make code look ugly very quickly. That is why the `async / await` syntax has been introduced: It allows you to write complex asynchronous code in a synchronous fassion while preserving the same semantics. – Marvin H. Jun 01 '19 at 00:11

2 Answers2

0

The best way to deal with asynchronous code is to work with async/await.

getRole: async (req, res) => {

try {

    let value = await User.findByPK(1);

    value = value.toJSON();

    if (!value) {
        console.log('No values obtained');
    }

    console.log(val)

}

catch (e) {

    console.log(e);

}

}
-1

There are several aproaches for this -

  • Define a variable at the top in the functional scope
let tempData;
const datas = roleService.getRoleById(1)
    .then(data => {
        var data = data.get({
            plain: true
        })
        console.log(data.get({
            plain: true
        }))
        tempData = data; //initializing variable
        // return data.get({ plain: true })
    })
    .catch((error) => res.status(400).send(error));
console.log('tempData is', tempData);
  • You can use async-await which is the best approach suggested by Terry Lennox
async function fetchData () {
    return roleService.getRoleById(1);
}
const data = await fetchData();
const tempData = data.get({ plain: true })
Siddharth Yadav
  • 383
  • 2
  • 9
  • 1
    You have do make sure your function is async, like he did above when he declared fetchData() – Greg Belyea Jun 02 '19 at 20:52
  • @HariharanAR an await keyword is only recognized inside an "async" function. Please do that and let me know if you still get any error. If not then please do accept my answer. – Siddharth Yadav Jun 17 '19 at 06:13