简体   繁体   中英

javascript promise return pending

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 };

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
    })
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM