1

I am trying to return an object from the function called getByUsername(). The correct object appears in the then() block. i'm unable to return that object from the outer function which returns undefined.

const url = 'https://jsonplaceholder.typicode.com/users/';

function get(url) {
  return fetch(url)
    .then(response => response.json());
}

const users = get(url)
  .then(users => users);

function getByUsername(x) {
  return users.then((user) => {
    return user.find((user) => {
      return user.username === x;
    });
  })
    .then((user) => {
      console.log(user); // Correct object
      return user;
    });
}

getByUsername('Kamren');
imnew123
  • 103
  • 2
  • 9
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Joe Clay Oct 27 '16 at 12:31
  • You don't, because you cannot know whether the promise is resolved already (hint: in your case it is not). – Bergi Oct 27 '16 at 12:36
  • I have read that but maybe i'm not getting the concept completely. The promise is resolved with the correct object but I want the function to return that object when it's ready – imnew123 Oct 27 '16 at 12:36
  • @Bergi How can I work around that? – imnew123 Oct 27 '16 at 12:37
  • 1
    You cannot do that (you don't want your entire function to block), the function always returns immediately but the result will take some time to be ready. Just return the promise (like you already do), and chain the `.then(function(user) { // correct object here` on the `getByUsername(…)` call. – Bergi Oct 27 '16 at 12:38

1 Answers1

2

getByUsername() returns a promise. You can't access the value immediately, it will be available only in the then() callback:

getByUsername('Kamren').then(user => console.log(user))

Alternatively, if you're using Babel, you can use transform-async-to-generator plugin and use an async function:

;(async () => {
  const user = await getByUsername('Kamren')
  console.log(user)
})()
Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177