1

I have function like this:

export function getAllUser() {
  let user;
  UserModel
    .find()
    .exec()
    .then((data) => {
      return data;
    })
    .catch((err) => {
      return err;
    });
}

How can I return data from this function? For example, I want to defind: user = getAllUser()

HKS
  • 167
  • 1
  • 2
  • 10

2 Answers2

1

As far as you are working with promises, you have to return the promise and treat it outside:

export function getAllUser() {
  let user;
  return UserModel
    .find()
    .exec()
    .then((data) => {
      return data;
    })
    .catch((err) => {
      return err;
    });
}

getAllUser()
.then(data => {
  // here you can access data
});
David Vicente
  • 3,091
  • 1
  • 17
  • 27
  • Thank @David, can you more specific how to use data from promise? In the example, you mean I call a function and assign data to variable inside `.then()`? – HKS Dec 11 '17 at 10:32
  • That's how promises work. When you call a function that return a promise, if you want to work with the value that is returned in the inside of the promise, you are going to get it into .then( Try the code I wrote and check it, and tell me if it works. – David Vicente Dec 11 '17 at 11:13
  • it work find. Thanks a lot. – HKS Dec 11 '17 at 15:00
0

You could use async/await like:

export async function getAllUser(){
  return await UserModel.find().exec();
}