1

I'm creating javascript function to get something using promise and async await. but i got Promise as return. can anyone help me? here is my code

 class NetworkError extends Error {
  constructor(message) {
    super(message);
    this.name = 'NetworkError';
  }
}

const fetchingUserFromInternet = (isOffline) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (isOffline) {
        reject(new NetworkError('Gagal mendapatkan data dari internet'), null);
      }
      resolve({ name: 'John', age: 18 });
    }, 500);
  })
  
};


const gettingUserName = async () => {
  const user = await fetchingUserFromInternet(false)
    .then((user) => {
      return user.name
    })
    .catch((rejectedReason) => {
      return rejectedReason
    })
};

module.exports = { fetchingUserFromInternet, gettingUserName, NetworkError };

hamzbond
  • 33
  • 5
  • 2
    `gettingUserName` function should return the `user`. Also note that you are mixing `async-await` syntax with promise-chaning - user either one of them, but not both. – Yousaf Apr 29 '21 at 07:05
  • 1
    `gettingUserName` function also has another problem: callback function of the `catch` method should _throw_ the `rejectedReason`, instead of returning it. Returning `rejectedReason` will implicitly convert promise rejection into promise fulfilment. See: https://stackoverflow.com/questions/62740112/using-then-on-a-failed-promise and https://stackoverflow.com/questions/62859190/handle-promise-catches-in-typescript – Yousaf Apr 29 '21 at 07:07

1 Answers1

3

Your gettingUserName method is never returning anything. You should do this:

const gettingUserName = async () => {
  try {
      const user = await fetchingUserFromInternet(false)
      return user.name;  
   } catch (e){
      return e;
   }
};

or this:

const gettingUserName = () => {
  return fetchingUserFromInternet(false)
    .then((user) => {
      return user.name
    })
    .catch((rejectedReason) => {
      return rejectedReason
    })
};
Jamiec
  • 133,658
  • 13
  • 134
  • 193