Reputation: 43
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 };
Upvotes: 1
Views: 526
Reputation: 136074
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
})
};
Upvotes: 3