0

While #1 returns the JSON object, #2 returns undefined.

How can I return data as JSON and access its properties (like data.username or data.email) ?

1

function username() {
    user.where('id', req.id).fetch().then(function (data) {
      data = data.toJSON();
      console.log(data);
    });
  }

  var adminJSON = username();

2

function username() {
    user.where('id', req.id).fetch().then(function (data) {
      data = data.toJSON();
      return data;
    });
  }

  var adminJSON = username();
  console.log(adminJSON);
salep
  • 1,332
  • 9
  • 44
  • 93

1 Answers1

1

It's because you are console logging adminJSON before the function has returned. The function is being run async.

You will either need to pass username a callback function as an argument, use an async library, or username return a promise.

user2263572
  • 5,435
  • 5
  • 35
  • 57